【问题标题】:Can we use height of image extracted from JQuery inside media query some how?我们可以在媒体查询中使用从 JQuery 提取的图像高度吗?
【发布时间】:2014-05-20 20:36:28
【问题描述】:

是否可以在媒体查询中使用具有图像高度的 java 脚本变量??

我的javascript代码是这样的

$(document).on('click', '.transparent-btns_nav',function(event){

    //alert('clicked');
    var images = $('.rslides ').find('img');
images.each(function(){ // jQuery each loops over a jQuery obj

    var h = $(this).outerHeight(true);// $(this) is the current image
    var w =  $(this).outerWidth(true);
    //alert('source:'+$(this).attr('src'));
    //alert('alto: '+h);
    if( h <290)
    {  
        var m = 290-h;
        m = m/2;
        var n = 290 - w ;
        n = n/2;
        //alert('less height');
        $(this).css('margin-top', +m + "px");
       $(this).css('margin-bottom', +m + "px");

    }

});
});

我的媒体查询代码是这样的

@media only screen 
and (min-device-width : 320px) 
and (orientation : portrait) {
#bg {
 max-height:290px;
 height:290px;
 margin:auto;
 margin-top:auto;
 overflow:hidden;
}
.thumb{
margin-top:-60px;

}
}

纵向模式下的媒体查询会添加 -60px top-margin 。但是当图像高度较小时,java脚本会在顶部和底部添加一些边距。 发生的情况是,对于小于外部 div 大小的图像,java 脚本和媒体查询的顶部边距变得太多。

谁能告诉我是否可以在媒体查询中使用 java 脚本中的 h 变量来检查图像的大小是否更小然后不添加 -60px 上边距。

提前致谢

【问题讨论】:

    标签: jquery html css media-queries


    【解决方案1】:

    您的问题的确切答案是否定的,您不能在媒体查询中使用 JavaScript 变量。

    但是有一种方法可以做你想做的事。

    如果图片很小,则使用 JS/jQuery 为其添加 CSS 类,例如

    $('.thumb').addClass('small');
    

    然后在您的媒体查询中:

    @media only screen and (min-device-width : 320px) and (orientation : portrait) {
      .thumb:not(.small) {
        margin-top: -60px;
      }
    }
    

    这里发生的情况是 CSS 边距仅添加到未被 JS 指定为小的拇指。

    【讨论】:

    • 但在我的网站中,即使图像更大,它也会添加类。
    • 例如看看这个小提琴jsfiddle.net/4PQLr/14 即使图像小于 if 语句,也会添加类。你能解释一下吗
    • 将 $('.thumb').addClass('small') 更改为 $(this).addClass('small') 以便您的选择器仅匹配您正在测量的图像。
    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 2013-07-29
    • 2017-06-21
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多