我正在尝试制作一个简单的程序,使我可以将鼠标悬停在一个图像上来查看另一个图像。我真的在如何处理鼠标悬停功能上苦苦挣扎。我意识到未声明imageNode,但是我不知道在哪里声明它以及它将存储什么引用。
如果有人可以指出正确的方向,以便在鼠标悬停时将image1替换为HTML中的另一个图像,然后在鼠标悬停时返回image1,我将不胜感激。我现在真的迷路了。
我在下面包括了HTML和JavaScript。
非常感谢
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
var image1 = $("image1");
var image2 = $("image2");
// preload images
var links = $("image_list").getElementsByTagName("a");
var i,
link,
image;
for ( i = 0; i < links.length; i++) {
link = links[i];
image = new Image();
image.src = link.href;
}
// attach mouseover and mouseout events for each image
image1.onmouseover = function(evt) {
link = this; //this is image that is mouseover
// set new image
//imageNode.src = link.getAttribute("href"
};
image1.onmouseout = function() {
};
image2.onmouseover = function() {
};
image2.onmouseout = function() {
};
};
<!DOCTYPE html>
<html>
<head>
<title>Image Rollover</title>
<link rel="stylesheet" type="text/css" href="rollover.css">
<script type="text/javascript" src="rollover.js"></script>
</head>
<body>
<main>
<h1>Fishing Images</h1>
<p>Move your mouse over an image to change it and back out of the
image to restore the original image.</p>
<ul id="image_list">
<li><a href="images/release.jpg" title="Catch and Release"></a></li>
<li><a href="images/deer.jpg" title="Deer at Play"></a></li>
<li><a href="images/hero.jpg" title="The Big One!"></a></li>
<li><a href="images/bison.jpg" title="Grazing Bison"></a></li>
</ul>
<p>
<img id="image1" src="images/hero.jpg" alt="">
<img id="image2" src="images/bison.jpg" alt="">
</p>
</main>
</body>
</html>
一个。
答案 0 :(得分:0)
如果您有类似<div id="image-rollover"></div>
的html,
您可以仅使用css这样在悬停时切换图像:
#image-rollover {
background-color: #000;
background-image: url('SOME_IMG_URL');
background-size: cover;
height: 100px;
width: 100px;
}
#image-rollover:hover {
background-image: url('SOME_OTHER_IMG_URL');
}
JSFiddle中的示例
答案 1 :(得分:0)
您可以通过一种简单的方法在Javascript中执行此操作:
var imgOnMouseOver = "OVER_IMG_URI";
var imgOnMouseOut = "OUT_IMG_URI";
var container = document.getElementById("IMG_TAG_ID");
container.addEventListener("mouseover", function(){
container.setAttribute("src", imgOnMouseOver);
});
container.addEventListener("mouseout", function(){
container.setAttribute("src", imgOnMouseOut);
});
示例程序可以正常运行:https://jsfiddle.net/praveen17/tv8xu67f/2/
答案 2 :(得分:0)
image1.onmouseover = function() {
image1.src="images/hero.jpg"
};
image1.onmouseout = function() {
image1.src="images/release.jpg"
};
image2.onmouseover = function() {
image2.src="images/deer.jpg"
};
image2.onmouseout = function() {
image2.src="images/bison.jpg"
};
};