在我的javascript程序中,我创建了一个页面,用于在用户移动mouseOver链接的同时显示图像和描述,并在用户移动链接的mouseOut时显示不带描述的不同图像。但是我没有按照期望获得mouseOver / mouseOut的输出。有人可以帮忙吗?我做了以下事情:
(i)当鼠标在链接上移动时,我通过传递文本和图像来调用该函数。
(ii)当鼠标移出时,我通过传递空白文本和不同图像来调用该函数。当鼠标离开所有链接时,此图像是相同的。
代码:
<!DOCTYPE html>
<html>
<head>
<style>
div a{
text-decoration: none;
font-size: 25px;
color: yellow;
}
.container {
width: 1002px;
margin-top: 50px;
margin-left: 130px;
}
#first {
width: 400px;
float: left;
height: 350px;
background-color:#f4b2ef;
border:inset;
}
#second {
width: 590px;
float: right;
height: 350px;
color: white;
border:inset;
}
</style>
<title>mouseover/out</title>
</head>
<body background="images/back.jpg">
<h1 style="text-align: center; font-family: monospace; color: white; font-size: 35px">PHOTO CONTEST </h1>
<div class='container'>
<div id="first">
<a href="#" onMouseOver="replaceImg(this)" onMouseOut="defaultImg(this)"><p style="text-align:center">First Place Winner</p></a>
<a href="#" onMouseOver="replaceImg2(this)" onMouseOut="defaultImg2(this)"><p style="text-align:center">Third Place Winner</p></a>
<a href="#" onMouseOver="replaceImg3(this)" onMouseOut="defaultImg3(this)"><p style="text-align:center">Merit Prize Winner</p></a>
<p id="para"> </p>
</div>
<div id="second">
<img id="default" src="images/default.jpeg" alt=""
width="590" height="350"/>
</div>
</div>
<script>
var blank = "";
var txt = "Beautiful fall";
var txt2 = "Natural pictures are beautiful";
var txt3 = "Beautiful Rose garden"
var w1 = new Image(590, 350);
var w2 = new Image(590, 350);
var w3 = new Image(590, 350);
var def = new Image(590, 350);
w1.src = "images/w1.jpeg";
w2.src = "images/w2.jpg";
w3.src = "images/w3.jpg";
def.src = "images/default.jpeg";
function replaceImg(txt, w1) {
w1.src;
var para = document.getElementById("para").innerHTML = txt;
}
function defaultImg(blank, def) {
def.src;
var para = document.getElementById("para").innerHTML = blank;
}
</script>
</body>
</html>
答案 0 :(得分:1)
我截断您的代码只是为了证明您可以通过使用js函数addEventListener("moustover",callback)
来完成工作。我从未以你的方式编写代码,所以我不知道如何改进你的代码。你应该总是分开你的html css和js代码。
var firstTarget = document.querySelector("#first");
firstTarget.addEventListener("mouseover",function(){
document.querySelector("#target-image").setAttribute("src",'https://via.placeholder.com/350x150)');
})
firstTarget.addEventListener("mouseout",function(){
document.querySelector("#target-image").setAttribute("src",'#');
})
<!DOCTYPE html>
<html>
<head>
<title>mouseover/out</title>
</head>
<body background="images/back.jpg">
<h1 style="text-align: center; font-family: monospace; color: white; font-size: 35px">PHOTO CONTEST </h1>
<div class='container'>
<div id="first">
<a href="#" ><p style="text-align:center">First Place Winner</p></a>
</div>
<div>
<img id="target-image" src="#" alt="">
</div>
</div>