我有这样一个 JavaScript
$(document).on('click', '.transparent-btns_nav', function(event) {
var images = $('.rslides ').find('img');
setTimeout(function() {
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) {
$(this).addClass('small');
var m = 290 - h;
m = m / 2;
// alert('less height');
$('.small').attr('style', 'margin-top:' + m);
// $('.small').css('margin-top', +m + "px");
// $('.small').css('margin-bottom', +m + "px");
}
if (h > 290) {
$(this).addClass('big');
var m = h - 290;
m = m / 2;
// alert('less height');
$('.small').attr('style', 'margin-top:' - m);
}
});
}, 1000);
});
媒体查询是这样的
@media only screen
and (min-device-width: 420px)
and (orientation: landscape) {
#bg {
}
#bg img {
margin - top: 0px;
}
.class {
margin-top: 0px;
margin-bottom: 0px;
}
.big {
margin-top: 0px;
margin-bottom: 0px;
}
}
我想做的是使用 JavaScript 向类 big
和 small
添加属性,并在模式时使用 MediaQuery
删除属性是风景。但是我做不到,有人可以帮我解决这个问题
更多说明
我正在尝试向大于或小于 div 的图像添加填充。就像它的高度小于顶部和底部的相等填充一样。如果图像的高度太大,那么我试图在顶部添加 -ve 填充并使图像居中。所有这些都是在纵向模式下动态完成的。如果手机变成横向,则应删除所有填充
最佳答案
我可以对您的代码提供少量输入。 代替“ATTR”,您可以直接使用“CSS”方法将内联样式应用于任何元素。
它的行为与属性样式相同。
代替这个:
$('.small').attr('style', 'margin-top:' + m);
你可以使用这个:
$('.small').css('margin-top',m);
输出将与您期望的相同:
class="small"style="margin-top:xx"
关于javascript - 是否可以使用 JQuery .attr() 标记向类添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23832848/