我希望当用户通过单击按住 div 时,div 的背景图像更改为“rustb.png”,然后在他们放开 div 时返回“rust.jpg”(停止按住点击)。这就是我所拥有的,当我点击 div 时它没有做任何事情。
<html>
<head>
<title> Img Change Testing </title>
</head>
<style>
#noclick {
background-image: url("rust.jpg");
width: 33%;
height: 50%;
left: 50%;
right: 50%;
background-size: 100% 100%;
}
#pushclick {
background-image: url("rustb.png");
width: 33%;
height: 50%;
left: 50%;
right: 50%;
background-size: 100% 100%;
}
</style>
<body>
<div id="noclick" onclick="mouseState(e)">
<p>This is an image</p>
</div>
</body>
<script>
$( "img.noclick" )
.mousedown(function() {
$( this ).prop("id", 'pushclick');
})
.mouseup(function() {
$( this ).prop("id", 'noclick');
});
</script>
</html>
请帮忙,谢谢!
最佳答案
你的代码有一些问题,
- 您没有任何图片标签
- 您正在使用不正确的类选择器访问 div。
- 您应该将 jQuery 事件绑定(bind)包装在 ready() 中
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Img Change Testing</title>
</head>
<style>
#noclick {
background-image: url("rust.jpg");
width: 33%;
height: 50%;
left: 50%;
right: 50%;
color: red;
background-size: 100% 100%;
}
#pushclick {
background-image: url("rustb.png");
width: 33%;
height: 50%;
left: 50%;
right: 50%;
color: green;
background-size: 100% 100%;
}
</style>
<body>
<div id="noclick">
<p>This is an image</p>
</div>
</body>
<script>
$(document).ready(function() {
$("div#noclick").mousedown(function() {
$(this).attr("id", 'pushclick');
})
.mouseup(function() {
$(this).attr("id", 'noclick');
});
});
</script>
</html>
关于javascript - 单击 div 更改图像时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997950/