我在jquery中有一个代码如下:
if($('div').width()>150){
$('#check').css('overflow-x', 'scroll');
$('#check').css('overflow-y', 'hidden');
}
我试图通过使用'this'关键字使这个代码更具体,这样css属性才会应用于特定的div。
任何人都可以告诉我做错了什么,因为'this'关键字在这种情况下不起作用。
答案 0 :(得分:1)
您可以使用filter()执行此操作
$('div').filter(function () {
return $(this).width() > 150;
}).css({
'overflow-x': 'scroll',
'overflow-y': 'hidden'
});
演示:Fiddle
答案 1 :(得分:1)
您需要对所有width
元素执行div
检查。为此,您可以使用filter
来获取宽度符合要求的元素,然后在其上设置CSS:
$('div').filter(function() {
return $(this).width() > 150;
}).css({
'overflow-x': 'scroll',
'overflow-y': 'hidden'
});
请注意,最好将类应用于元素而不是直接更改CSS,因为它可以更好地分离关注点:
$('div').filter(function() {
return $(this).width() > 150;
}).addClass('horizontal-scroll');
.horizontal-scroll {
overflow-x: scroll;
overflow-y: hidden;
}
答案 2 :(得分:1)
我的版本是'this',希望它会有所帮助
$('div').each(function(){
if ($(this).width() > 150) {
$(this).css('overflow-x', 'scroll');
$(this).css('overflow-y', 'hidden');
}
});
答案 3 :(得分:0)
您应该从jquery
each
$.each($('div'),function(){
if($(this).width()>150){
$(this).css('overflow-x', 'scroll');
$(this).css('overflow-y', 'hidden');
}
})
答案 4 :(得分:0)
<div class="scroll">
this is going to be a test, in which the text will overflow.
this is going to be a test, in which the text will overflow.
this is going to be a test, in which the text will overflow.
this is going to be a test, in which the text will overflow.
this is going to be a test, in which the text will overflow.
</div>
<div class="scroll">
this is going to be a test, in which the text will not overflow.
</div>
$(".scroll").each(function() {
if ($(this).width() > 150) {
$(this).css('overflow-x', 'scroll');
$(this).css('overflow-y', 'hidden');
}
});
答案 5 :(得分:0)
试
$(document).ready(function () {
$('div').each(function () {
if ($(this).width() > 150) {
$(this).css({
'overflow-x': 'scroll',
'overflow-y': 'hidden'
});
}
});
});