Customize background image using javascript

In chrome, safari and opera, setting the background image to an absolute link, for example: "/images/image.png", changes it to " http: //sitepath/images/image.png ".

He does not do this in firefox.

Is there a way to avoid this behavior, or is it written in the javascript engine browser? Using jquery to set the background image also makes this problem.

The problem is that I am posting HTML to a php script that needs URLs in this particular format. I know that adjusting the relative path to the image corrects this, but I cannot do this.

The only alternative would be to use a regular expression. to translate urls.

Thank.

Check it out in Firefox browser and Chrome / webkit browser:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div style="height:400px;width:400px;background-image:url(/images/images/logo.gif);">
</div>
<br />
<br />
<div id="test" style="height:400px;width:400px;">
</div>
<script type="text/javascript" src="/javascripts/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#test").css('background-image',"url(/images/images/logo.gif)");
        alert(document.getElementById('test').style.backgroundImage);
    });
</script>
</body>
</html>
+3
source share
3 answers

Not sure if you put this location in the document, but you can use window.location.hostnameto get the domain and add it.

var bgImg = window.location.hostname + '/images/images/logo.gif';
$("#test").css('background-image', 'url('+bgImg+')');

You would replace /images/images/logo.gifwith what you generated the image (server side, I think?)

+2
source

A better approach would be to change the classes on the element so that the new class changes the image to whatever you want. Sort of:

$("#test").addClass("newClass");

This is a much cleaner approach that will deteriorate better and ensure proper separation of problems.

CSS, , .

$("#test").css("background", "url(" + window.location.hostname + "/logo.gif)");
+2
$('#divID').css("background-image", "url(/myimage.jpg)");  
-1
source

Source: https://habr.com/ru/post/1743639/


All Articles