简体   繁体   English

单击div更改图像时

[英]When clicking on a div change image

I want the background image of the div to change to 'rustb.png' when ever the user is holding down on the div with a click and then return to 'rust.jpg' when they let go of the div (stop holding down click). 我希望当用户单击并按住div时,将div的背景图像更改为“ rustb.png”,然后当他们放开div时,返回到“ rust.jpg”(停止按住click )。 This is what I have and it isn't doing anything when I click on the div. 这就是我所拥有的,当我单击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>

Please help, thanks! 请帮忙,谢谢!

Your code has some issues, 您的代码存在一些问题,

  1. You dont have any image tag 您没有任何图像标签
  2. You are accessing div using class selector which is incorrect. 您正在使用不正确的类选择器访问div。
  3. You should wrap your jQuery event binding in ready() 您应该将jQuery事件绑定包装在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> 

 <div id="noclick" onclick="mouseState(e)">
    <p>This is an image</p>
  </div>

$("#noclick").on("mousedown", function() {
    $( this ).attr("id", 'pushclick');
   });
$("body").on("mouseup","#pushclick",function() {
  $( this ).attr("id", 'noclick');
   });

fiddle link here 小提琴链接在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM