[1] 如何在 img src 悬停时更改它
您不能仅使用 CSS 来做到这一点,因为 src 是 DOM 属性 而不是 CSS 属性, HTML DOM 事件系统需要一些 javascript 来完成此操作
<body>
<div>
<img onmouseenter="highlight(this)" onmouseleave="unhighlight(this)"
src="thumbnail1">
<a href="#potato" class="hoverable-link">Some Link</a>
</div>
<script>
function highlight(image) {
image.src = "thumbnail2"; //Blue Image
}
function unhighlight(image) {
image.src = "thumbnail1"; //Gray Image
}
</script>
</body>
JsFiddle:https://jsfiddle.net/f0c7p3tL/2/
DOM 事件列表:http://www.w3schools.com/jsref/dom_obj_event.asp
另一种方法是根本不使用 src DOM 属性。相反,您可以使用 background CSS 属性,这样您就可以利用 CSS:hover 选择器
CSS:
#my-thumbnail {
background: url("/thumbnail1") no-repeat;
width: 32px;
height: 32px;
}
#my-thumbnail:hover {
background: url("/thumbnail2") no-repeat;
}
HTML:
<div>
<img id="my-thumbnail">
<a href="#potato" class="hoverable-link">Some Link</a>
</div>
JsFiddle:https://jsfiddle.net/7xoprwky/
[2] 如何同时触发两个元素的悬停事件
同样,这里有两种方法可用。
首先是使用 javascript 和 HTML DOM 事件。在这种方法中,我们希望它们在周围的<div> 父元素上触发,而不是在任何一个子元素上触发事件。然后,在事件处理程序中,我们选择子元素并相应地更改它们的 DOM 属性
<body>
<div onmouseenter="highlight(this)" onmouseleave="unhighlight(this)">
<img id="my-thumbnail" src="thumbnail1">
<a id="my-anchor" href="#potato">Some Link</a>
</div>
<script>
var myThumbnail = document.getElementById('my-thumbnail'),
myAnchor = document.getElementById('my-anchor');
function highlight() {
myThumbnail.src = "/thumbnail2";
myAnchor.style.color = "blue";
myAnchor.style.fontWeight = "bold";
}
function unhighlight() {
myThumbnail.src = "/thumbnail1";
myAnchor.style.color = "gray";
myAnchor.style.fontWeight = "normal";
}
</script>
</body>
JsFiddle:https://jsfiddle.net/2uthconL/
在第二种方法中,我们利用 CSS 选择器语法从周围的 div 中突出显示我们的内部元素
CSS:
#my-thumbnail-link {
}
#my-thumbnail-link img { /* Select all img tag inside div */
background: url("/thumbnail1") no-repeat;
width: 32px;
height: 32px;
}
#my-thumbnail-link:hover img { /* Select all img tag inside div when it is hovered */
background: url("/thumbnail2") no-repeat;
}
#my-thumbnail-link a { /* Select all a tag inside div */
color: gray;
}
#my-thumbnail-link:hover a { /* Select all a tag inside div when it is hovered */
color: blue;
font-weight: bold;
}
HTML:
<div id="my-thumbnail-link" class="vcenter-parent">
<img class="vcenter-child">
<a href="#potato" class="vcenter-child">Some Link</a>
</div>
JsFiddle:https://jsfiddle.net/x61dy0mk/2/
更多关于 CSS 选择器:http://www.w3schools.com/cssref/css_selectors.asp
如果您的缩略图只是一个静态资产,我推荐 CSS 方法而不是 Javascript HTML DOM 方法,因为它的可读性和可维护性(想象一下保留数千个事件处理程序)