简体   繁体   English

Javascript-根据URL的最后一个字符串动态更改背景图片

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

I have had some help from @Ariel Davis. 我从@Ariel Davis获得了一些帮助。 My URLS are dynamically generated from a single template. 我的URL是从单个模板动态生成的。 I want the background image of the dynamically generated page to match the URL. 我希望动态生成的页面的背景图像与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. 示例:URL: http : //my.mysite.com/media/surfing ,我想在/ assets / main / img /文件夹'surfing.jpg中动态获取图像并将其显示为背景。

Here is my current CSS: 这是我当前的CSS:

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

}

My current Javascript: 我目前的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: 尝试在结束body标记之前添加以下代码:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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