1、新建一个html文件,命名为test.html。
2、在test.html文件中,使用div标签创建一个模块,并设置其id属性为tid,下面将通过该id设置其css样式。
3、在css标签内,对div进行样式设置,使用width属性设置div的宽度为200px,使用height属性设置div的宽度为20px,使用background属性设置div的背景颜色为红色。
4、在css标签内,再定义一个类名为newbg的样式,使用background属性设置背景颜色为黄色。
5、在test.html文件中,给div绑定onmouseover鼠标移动事件,当鼠标移动至div时,执行myfun()函数。
6、在test.html文件中,在js标签内,创建一个myfun()函数,在函数内,使用getElementById()获得div对象,通过className(newbg)设置div的新背景颜色。
以下直接可以运行。如果DIV在ID为area的div中,即可拖拽。我在Drag函数里做了对父div的判断。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />
<title>鼠标拖拽</title>
<script type="text/javascript">
function Drag(o, e){
if(o.parentElement!=document.getElementById('area')) return
var e = window.event || e
var _x = e.offsetX || e.layerX
var _y = e.offsetY || e.layerY
o.style.filter = 'Alpha(opacity=70)'
o.style.opacity = '0.7'
document.onmousemove = function(e){
var e = window.event || e
o.style.left = e.clientX - _x + 'px'
o.style.top = e.clientY - _y + 'px'
o.style.cursor="move"
}
document.onmouseup = function(e){
document.onmousemove = null
o.style.filter = o.style.opacity = ''
o.style.cursor="default"
}
}
</script>
</head>
<body>
<div id='area'>
<div onmousedown="Drag(this, event)" style="position:absoluteborder:1px solid redbackground:pinkwidth:400pxheight:300px"></div>
</div>
<div onmousedown="Drag(this, event)" style="position:absoluteleft:500pxborder:1px solid redbackground:pinkwidth:400pxheight:300px"></div>
</body>
</html>
1、输入代码,其中button是鼠标要滑动的地方,滑过button时,class为content的内容就要显示出来,鼠标滑出去的时候,这块内容就需要重新隐藏起来。
2、把黑色内容的部分初始状态写成隐藏。只需要在class为content里写上display:none,即可。
3、来看下代码和浏览器中的效果。可以看到黑色内容部分已经不见了。
4、把onmouseover和onmouseout两个事件作用在button上面,再写overShow()和overHide()两个 函数。可以看到在函数中通过改content的display属性来实现显示隐藏的效果。
5、在浏览器中就可以看到效果了。