如何从JavaScript获取Onclick图像落后于所有其他图像

时间:2017-03-14 19:04:56

标签: javascript jquery css

我试图让splatter.png一旦点击它们就会落后于所有的GIF。我尝试过使用Z-Index,但它似乎并没有起作用。这只是设置错了吗?或者有其他方法来设置它吗?

HTML
         

<head>

<title>Movement</title>

<style>

div.a {
width: 200px;
height:200px;
position:absolute;
background-image: url("ant.gif");
z-index: -1;
   }

</style>

<script src="jquery-3.1.1.js"></script>
<script src="please-work.js"></script>


</head>

<body>

<div class="animatedDivs"></div>


</body>

</html> 

的JavaScript

$(document).ready(function () {
newDiv();
newDiv();
newDiv();
});

function newDiv() {
var $div = $("<div class='a'>");
$(".animatedDivs").append($div);
animateDiv();


$div.click(function(){
    $div.css('background-image','url(splatter.png)', ('z-index', -10));
    //$(this).data('clicked', true);
    var offset = $div.position();
    $div.stop(); 
    $div.position({left:(offset.left), right: (offset.right)});
    });


    function animateDiv() {
    var newq = makeNewPosition();
    var oldq = $div.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $div.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function () {
        animateDiv();
    });


};


}

function makeNewPosition() {

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh, nw];

}

function calcSpeed(prev, next) {

var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);

var greatest = x > y ? x : y;

var speedModifier = .1;

var speed = Math.ceil(greatest / speedModifier);

return speed;

}

1 个答案:

答案 0 :(得分:0)

问题在于您分配css方法的位置。

 $div.css('background-image','url(splatter.png)', ('z-index', -10));

jQuery.css()函数不能有三个参数。您可以传递两个参数(名称,值)或json对象(名称值对)

 $div.css('background-image', 'url(splatter.png)').css('z-index', -10);

$div.css({'background-image':'url(splatter.png)','z-index':-10});