javascript - 单击 div 更改图像时

标签 javascript jquery html css

我希望当用户通过单击按住 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>

请帮忙,谢谢!

最佳答案

你的代码有一些问题,

  1. 您没有任何图片标签
  2. 您正在使用不正确的类选择器访问 div。
  3. 您应该将 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/

相关文章:

javascript - 通过ajax和jsp将javascript变量保存到MySql数据库

java - 前端和后端的电子邮件验证解决方案

javascript - 文本框可以一半只读一半可编辑吗

javascript - 防止JS点击计数器出现负数

html - CSS : creating cornered border using css

html - 垂直对齐 flexbox

jquery - 从下拉列表中检索选择并填充列表

jquery - Tomcat CORS 过滤器和 Spring Security

jquery - 使用 jquery ajax 或 post 插入 DOM 时如何停止评估脚本标签

javascript - 如何在点击时更改图像的 ng-src