代码有bug,修改后如下:
需要注意,拷贝下面这段代码,保存为 html后缀名的文件;需要自己在相同的目录下,放置两张图片,小图片.jpg 大图片.jpg
效果如下图:当鼠标悬停在小图片上面的时候,会显示大图片;鼠标移出,隐藏大图片。
问题:定位需要读者自己去实现一下吧,偷懒了。感谢楼上分享!
<!doctype html><html>
<head>
<meta charset=utf-8>
</head>
<body>
你要显示特效的html
<img src="小图片.jpg" width="200px" height="200px" id="littleimg" onmouseout="hoverHiddendiv()" onmouseenter="hoverShowDiv()" />
<div style="width:200pxheight:80pxborder:1px solide #aaccffdisplay:none" id="divHover" >
大图片显示如下
<img src="大图片.jpg" width="500px" height="300px" id="bigimg" />
</div>
<script type="text/javascript">
let divHover = document.getElementById("divHover")
function hoverShowDiv() {
console.log("显示大图片")
divHover.style.display = "block"
divHover.style.top = document.getElementById("littleimg").style.top + 10
divHover.style.left = document.getElementById("littleimg").style.left + 10
}
function hoverHiddendiv() {
console.log("显示小图片")
divHover.style.display = "none"
}
</script>
</body>
</html>
第一:js进行鼠标悬停事件来处理DOM实际上是不合理的。对于界面交互上能通过css处理的事件就不要用js来处理;
第二:恰好css对于鼠标悬停是有对应的选择器及其处理;
处理方法:如图A:
假设A的id为a,css代码如下:
#a{width:100px
height:36px
float:left
}
//对于位置的固定可以自行选择处理,当前用float固定。
#a:hover{
width:200px
}
结果将会如你图中所需要的完成。
如必须用JS处理的话,代码如下:
//既定a的样式已明确://html代码:
<span id='a' onmouseover="fc1(this)"
onmouseout="fc2(this)"></span>
<script>
function fc1(node){
node.style.width = '200px'
}
function fc2(node){
node.style.width = '100px'
}
</script>
如<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />
1、<html>
2、<head>
3、<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />
4、<title>JS教程:鼠标悬停时显示文字或显示图片</title>
5、<script language="javascript">
6、functionshowPic(sUrl{varx,yx=event.clientXy=event.clientYdocument.getElementById("Layer1").style.left=xdocument.getElementById("Layer1").style.top=ydocument.getElementById("Layer1").innerHTML = "<img src=\"" + sUrl + "\">" document.g
7、function hiddenPic(){ document.getElementById("Layer1").innerHTML = ""document.getElementById("Layer1").style.display = "none"}
8、</script>
9、</head>
10、<body>
11、<div id="Layer1" style="display:noneposition:absolutez-index:1"></div>
12、<img src="#########" onmouseout="hiddenPic()"
13、onmousemove="showPic(this.src)" title="wowowowo" /> //此行title实现悬停时显示文字onmousemove实现显示图片
14、<p></p>
15、</body>
16、</html>