题
<div><span>shanghai</span><span>male</span></div>
对于像上面这样的div,当鼠标放在上面时,它应该变成光标:指针,并且当单击时,触发一个
javascript函数,如何完成这项工作?
编辑:鼠标打开时如何更改div的背景颜色?
再次编辑:如何使第一个跨度的宽度= 120px?似乎在firefox中不起作用
解决方案
给它的ID,如 “东西”,则:
var something = document.getElementById('something');
something.style.cursor = 'pointer';
something.onclick = function() {
// do something...
};
更改背景色(按照更新的问题):
something.onmouseover = function() {
this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
this.style.backgroundColor = '';
};
其他提示
<div style="cursor: pointer;" onclick="theFunction()">
是最简单有效的事情。
当然,在最终的解决方案中,您应该将标记与样式(css)和行为(javascript)分开 - 阅读它 在分开的名单上 不仅可以解决这个特定问题,而且可以解决一般标记设计的良好实践。
我建议使用jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
我建议使用一个CSS类称为clickbox和与jQuery激活它:
$(".clickbox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
现在你要做的唯一事情就是标记您的DIV可点击,并提供一个链接:
<div id="logo" class="clickbox"><a href="index.php"></a></div>
加一个CSS样式改变鼠标光标:
.clickbox {
cursor: pointer;
}
简单,不是吗?
当你更新你的问题,这里是一个obtrustive例如:
window.onload = function()
{
var div = document.getElementById("mydiv");
div.style.cursor = 'pointer';
div.onmouseover = function()
{
div.style.background = "#ff00ff";
};
}
<div style="cursor: pointer;" onclick="theFunction()" onmouseover="this.style.background='red'" onmouseout="this.style.background=''" ><span>shanghai</span><span>male</span></div>
这将改变背景颜色,以及
其中最简单的是:
<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
不隶属于 StackOverflow