单击div更改图像时

时间:2016-12-06 14:40:09

标签: javascript jquery html css

我希望div的背景图片更改为' rustb.png'当用户用点击按住div时,然后返回到' rust.jpg'当他们放开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>

请帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

您的代码存在一些问题,

  1. 您没有任何图片标记
  2. 您正在使用不正确的类选择器访问div。
  3. 您应该将您的jQuery事件绑定包装在ready()
  4. <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>

答案 1 :(得分:1)

 <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