繁体   English   中英

使用JQuery设置背景图片ID

[英]Set background-image ID using JQuery

我想根据用户设备大小使用不同的背景。 我已经使用JQuery设置了背景图像,那里没有问题。 现在,我需要设置背景图像的ID,但似乎无法弄清楚。 我需要将ID设置为bg,以用于下面的另一个脚本。

请帮忙!

谢谢

var theDiv = document.getElementById("body");
 if (screen.width <= 1300) {
    $('body').css('background-image', 'url(images/jpg/SmallLeather.jpg)');}
else{
    $('body').css('background-image', 'url(images/jpg/BackGroundCon.jpg)');
    $('body').css('background-image', 'id (bg)');}
</script>  
<script>
$(window).load(function() {    
    var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();
function resizeBg() {
    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }
}
theWindow.resize(resizeBg).trigger("resize");
});
</script>

背景图片没有自己的ID。 设置为背景的对象可以具有id。 然后,可以通过找到具有该ID的宿主对象,然后在该对象上设置背景图像来获取背景图像。

如果有问题的对象是主体,则实际上不需要ID即可检索该对象,因为您可以随时将其称为document.body javascript中有对该对象的内置访问。

另外,您可以使用CSS媒体查询完全使用CSS(无javascript)基于窗口大小动态调整背景图像。

使用attr()将正文的id属性设置为bg

$('body').attr('id', 'bg');

您无法设置背景图片ID,因为它没有一个。 我建议使用.addClass()添加所需的ID(现在是一个类),或者如果主体尚无ID,则使用.attr("id", "bg")设置ID身体标签。 然后通过.css("background-image")获得背景图像。

更新:似乎您想调整背景图片的大小。 如果是这样,请考虑使用background-size: covercontain在CSS中。 在使用时,也可以使用答案之一中提到的媒体查询

var id = $('body').attr('id');
$("#"+id).css('background-image', 'url(BackGroundCon.jpg)');

这是我想出的解决方案。

<img src="images/jpg/BackGroundCon.jpg" id="bg" alt=""> 
<script type="text/javascript">
var theDiv = document.getElementById("body");
if (screen.width <= 1300) {
var img= 'images/jpg/SmallLeather.jpg';
$('#bg').attr("src",img); 
 }

</script><script>
$(window).load(function() {    
var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();
function resizeBg() {
    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }
}
theWindow.resize(resizeBg).trigger("resize");
});
</script>

至少在目前,它在起作用。 http://heretomeet.com

StackExchange不允许我接受您的多个答复,这很遗憾,因为你们中的许多人在凌晨2:00收到了真正有用的评论! 你们什么时候睡觉?

谢谢

暂无
暂无

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

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