简体   繁体   中英

Change CSS Background Image for KEYBIND Javascript DIV

I am using the following to contain a div within borders. The DIV is attached to each arrow key. How can I change the background image of #body per each key-direction?

<script>
var pane = $('#border'),
box = $('#body'),
w = pane.width() - box.width(),
d = {},
x = 3;

function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}

$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });

setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
</script>

<div id="border">
<div id="body">
<div class='head'></div>
</div>
</div>

#border{position:relative; width:300px; height:300px; border:2px solid red;}
#body{position:absolute; top:140px; left:140px; width: 70px; height: 70px; background: url('/images/model.png');}
#body .head{width: 70px; height: 25px; top: 0; background: rgba(0,0,0,0.5);}

Whenever any keypress/keydown events are fired change the background-image attribute using the css method of jquery.

$('.background').css('background-image','url(images/any_image.png)');

In your case it might be something like this,

$(window).keydown(function(e) { 
    d[e.which] = true; 
    $('#body').css('background-image','url(http://hdlatestwallpapers.com/wp-content/uploads/2013/12/Tom-and-Jerry-Cartoon-Wallpaper.jpg)');
});

Not sure how you are getting the images. If you can get random images on each keydown/keyup then you can change the url and have difference backgrounds. Same goes for keyup event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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