I'm trying yo change the background of a DIV, and I think that my code is correct, but it seems no. I think the error is on the URL parameter because without parameter the function works.
This is my code:
<script language="JavaScript">
function imagen(col){
document.write(col);
var elem = document.getElementById("fondo");
elem.style.backgroundImage = url('col');
}
</script>
<div class="grid-block" id="fondo" width: 100%; height: 100vh;">
<div class="heading">
<a href="pagina1.html" onMouseOver="imagen(uploads/banner-01.jpg)" >Rojo</a>
</div>
</div>
Thank you.
The argument to imagen()
needs to be in quotes. Otherwise it will be evaluated as an expression, and you'll get a syntax error.
You need to use string concatenation to combine the argument with url()
.
Don't use document.write()
in functions that run after the DOM is loaded. It will clear the DOM -- see Why is document.write considered a "bad practice"? Use console.log()
for debugging output.
function imagen(col) { console.log(col); var elem = document.getElementById("fondo"); elem.style.backgroundImage = 'url(' + col + ')' }
<div class="grid-block" id="fondo" width: 100%; height: 100vh; "> <div class="heading "> <a href="pagina1.html " onMouseOver="imagen('uploads/banner-01.jpg') " >Rojo</a> </div> </div>
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.