简体   繁体   English

使用img src作为背景图像

[英]Use img src as background-image

I'm trying to use img src as background-image when media queries is in use. 我正在尝试在使用媒体查询时将img src用作背景图像。

My media queries is actived while max-width: 854px. 最大宽度:854像素时,我的媒体查询处于活动状态。

I'm trying it with jQuery but don't work. 我正在尝试使用jQuery,但无法正常工作。

My jQuery: 我的jQuery:

$(document).ready(function () {
        if ($(window).width() <= 854) {
            $('a.class').css('background-image', 'url(' + $('a.class img').attr(src) + ')');
        }
    });

What am I doing wrong? 我究竟做错了什么?

Thank you! 谢谢!

Doing it with jQuery, you will probably want to do this : 使用jQuery进行此操作,您可能需要这样做:

$(document).ready(function () {
    if ($(window).width() <= 854) {
        $('a.class').each(function(){
            $(this).css('background-image', 'url(' + $(this).children('img').attr('src') + ')');
        });
    }
});

I used an each loop because I guess you could have multiple a.class and I use quotes for the src attribute. 我使用了each循环,因为我猜您可能有多个a.class并且对src属性使用了引号。

Change 更改

$('a.class').css('background-image', 'url(' + $('a.class img').attr(src) + ')');

to

$('a.class').css('background-image', 'url(' + $('a.class img').attr('src') + ')');

The .attr function expects a string. .attr函数需要一个字符串。 You needed to quote the value since src is the name of the attribute. 您需要用引号引起来,因为src是属性的名称。

You probably would have caught this if you checked your browser's consoles for errors as Juan suggested. 如果您按照Juan的建议检查浏览器的控制台中的错误,则可能会发现此错误。 Or if you looked at the syntax highlighting in your IDE you'd notice that src was colored like variable name instead of a string value. 或者,如果您查看IDE中突出显示的语法,您会发现src颜色像变量名而不是字符串值。

$('a.class').css('background-image', 'url(' + $('a.class img').attr("src") + ')'); $('a.class')。css('background-image','url('+ $('a.class img')。attr(“ src”)+')');

"src" has to be between quotes. “ src”必须在引号之间。

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

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