简体   繁体   English

根据背景图像大小调整div大小的脚本 - 在Firefox中不起作用

[英]Script that resizes div based on background-image size — Not working in Firefox

I have this script that resizes the height of a div, based on the height of the background image that is set for it. 我有这个脚本,根据为其设置的背景图像的高度调整div的高度。

$(document).ready(function() {
    var url = $('#header').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
    var bgImg = $('<img />');
    bgImg.hide();
    bgImg.bind('load', function()
    {
        var height = $(this).height();
        $("#content").css("margin-top",height+"px");
        $("#header").css("min-height",height+"px");
    });
    $('#header').append(bgImg);
    bgImg.attr('src', url);
});

For some reason, it works just fine in both Chrome and Safari, but not in Firefox. 出于某种原因,它在Chrome和Safari中都可以正常工作,但在Firefox中则不行。 I've checked the console in FF to see if there are any errors, but there are none. 我已经检查了FF中的控制台,看是否有任何错误,但没有。 Not sure if there is something here incompatible with FF or some weird FF thing that I'm not familiar with. 不确定这里是否有与FF不兼容的东西或者我不熟悉的一些奇怪的FF事物。 Any comments appreciated. 任何评论赞赏。

The problem is that .replace("'", '') and .replace('"', '') only replace the FIRST quote. 问题是.replace("'", '').replace('"', '')仅替换FIRST引用。

Then, you can use regular expressions with the g (global) flag: .replace(/'/g, '') and .replace(/"/g, '') . Or even better, join them all: 然后,你可以使用带有g (全局)标志的正则表达式: .replace(/'/g, '').replace(/"/g, '') 。或者更好的是,将它们全部加入:

.replace(/url\(|\)|'|"/g, '');

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

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