2016-12-06 195 views
-1

我想要div的背景图像更改为'rustb.png',当用户点击时按住div,然后返回'rust.jpg'时放开div(停止点击)。这是我所拥有的,当我点击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> 

请大家帮忙,谢谢!

+0

你在浏览器的控制台中看到什么错误? – j08691

+0

@ j08691“Moustate没有定义”? –

+0

这是唯一的错误?如果是这样,为什么你有'onclick =“mouseState(e)”'? – j08691

回答

1

你的代码中有一些问题,

  1. 你不要有任何图片标签
  2. 您正在使用类选择这是不正确访问股利。
  3. 你应该换你的jQuery事件绑定就绪()

<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
<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