简体   繁体   中英

How to change background-image ondragenter or ondragover with javascript

I have a div with an ondragenter event. When the mouse is entering the div, I want the background to change to a specific image, but the image doesn't change until I let the mouse button up.

If I try to change to a background color, it works fine! I have also tried to change css class with a background-image and it works, but in my case I can't do that because I don't know which image to show from the css.

HTML

<div id="test" ondrop="drop(event)" ondragenter="enter(event)"></div>

JavaScript

function enter(event) {
    $('#test').css('background', '#333 url("test.png")');
    event.preventDefault();
}

In my code example the div will get the color #333 when the mouse enters and then get the background image when I let the mouse button up.

I'm developing this in spotify which is webkit-based. Does anyone have a clue how I can solve this problem?

Thank you!


On http://musicmachinery.com/2011/12/02/building-a-spotify-app/ , it says:

Developing a Spotify App is just like developing a modern HTML5 app. You have a rich toolkit: CSS, HTML and Javascript. You can use jQuery, you can use the many Javascript libraries. Your app can connect to 3rd party web services like The Echo Nest. The Spotify Apps supports just about everything your Chrome browser supports with some exceptions: no web audio, no video, no geolocation and no Flash (thank god).

That being said, I recommend that you use Jquery. Not only is it easy to learn, but you have have access to JQuery UI (visit http://jqueryui.com/demos/ for demos).

As for your drag-enter/drop problem, I've made you an example using jquery. The demo can be found on HERE or http://jsfiddle.net/H8fPL/12/ . I've also provided the code I used below. Let me know if you need anything else! Happy coding!

CSS:

div{
 width:200px;
 height:220px;
 border:1px solid black;    
}

#div1{
 background-color:orange;
 margin-left:20px;
}

.NC{
 background:url("http://www.dreadcentral.com/img/news/jun11/niccage.jpg") no-repeat;   
}

.surprised{
background:url('http://rlv.zcache.ca/smiley_oh_sticker-p217194901605792400envb3_400.jpg');
background-size:80px 60px;
background-repeat:no-repeat;
background-position:center;
}

JAVASCRIPT:

//needed for jquery, 
//CALL THIS SCRIPT BEFORE USING $ syntax
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
//query UI script
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>

HTML:

<div id='div1'>
Come Hither...
</div>

<div id="dropme">
DRAG ME OVER AND WATCH ME CHANGE
</div>



IMPORTANT REFERENCES:

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