是否可以在媒体查询中使用具有图像高度的 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 top-margin 。
提前致谢
最佳答案
您问题的准确答案是否定的,您不能在媒体查询中使用 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 指定为小的缩略图。
关于jquery - 我们可以在媒体查询中使用从 JQuery 中提取的图像高度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23759677/