简体   繁体   中英

Javascript- Dynamicly Change Background Image Based On The Last String Of The URL

I have had some help from @Ariel Davis. My URLS are dynamically generated from a single template. I want the background image of the dynamically generated page to match the URL.

EXAMPLE: URL: http://my.mysite.com/media/surfing , I would like to dynamically get the image in my /assets/main/img/ folder 'surfing.jpg and display it as the background.

Here is my current CSS:

.main_background{
background: url('/assets/main/img/athlete_background.jpg') no-repeat  top center;
background-size: cover; 
min-height:600px;

}

My current Javascript:

$(function () {
    //Change banner image
    var loc = window.location.pathname
    var img = loc.substring(
        loc.lastIndexOf("/") + 1, loc.length
    ) + ".jpg"
    $("main_background").css( 
        "backgroundImage",
        "url(" webroot/assets/main/img/ + img + ")" 
    )
})

Any help would be greatly appreciated, thank you.

Try adding this just before the closing body tag:

<script>
    (function(){ 
        var loc = window.location.pathname;
         var img = loc.substring(
             loc.lastIndexOf("/") + 1, loc.length
             ) + ".jpg";

        $(".main_background").css("backgroundImage", "url('webroot/assets/main/img/" + img + "')");
    }());
</script>

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