我想在767px上隐藏所有没有data-web-src
属性的图像。我试过以下但是我失败了;我怎样才能做到这一点?
$('#homepage-carousel .lazy_res').each(function(index, value) {
var ws = $(window).width();
var large = 1024;
var medium = 767;
var small = 0;
if (ws <= medium) {
$(this).not('[data-web-src]').hide();
} else {
$(this).not('[data-web-src]').show();
}
});
img {
width: 500px;
float: left;
margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="homepage-carousel">
<img class="lazy_res" src="http://pre07.deviantart.net/338a/th/pre/i/2012/007/f/7/mapa_mundi_com_bandeiras___preto_by_plamber-d4leocd.jpg" alt="" />
<img class="lazy_res" src="http://img05.deviantart.net/a6be/i/2013/099/8/9/helena_harper_by_plamber-d6125tx.jpg">
</div>
答案 0 :(得分:3)
这应该通过 CSS Media Queries 来完成。无需JavaScript。
def _find_bracket_n(str,left_brac,brackets_num)
i = 0
num_of_left_bracs = 0
while i < str.length && num_of_left_bracs < brackets_num
num_of_left_bracs += 1 if str[i] == left_brac
i += 1
end
n_th_lbrac_index = i - 1
end
/* Set page default styles and styles that should only
be in effect for viewports under 767px wide here. */
img {
width: 500px;
float: left;
margin-right: 10px;
}
/* Apply the following CSS only to viewports wider than 767px */
@media (min-width: 767px) {
/* Select all images except those with an attribute of: dat-web-src */
img:not([data-web-src]) {
display: none; /* Hide the matching elements */
}
/* Make any other CSS changes you like here */
/* This class will only be applied to images when the media query
is in effect. */
img.someNewClass {
/* Whatever you need here */
}
}
答案 1 :(得分:1)
您需要在函数中设置代码,然后可以调用onload
以及onresize
来测试它:
见https://codepen.io/gc-nomade/pen/EXLZEN
描述:将一个或多个事件的事件处理函数附加到所选元素。
function testit() {
$("#homepage-carousel .lazy_res").each(function(index, value) {
var ws = $(window).width();
var large = 1024;
var medium = 767;
var small = 0;
if (ws <= medium) {
$(this).not('[data-web-src]').hide();
} else {
$(this).not('[data-web-src]').show();
}
});
}
$(window).on('resize load', testit );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below 767px wide, you'll see nothing else here :), use the full page mode to test the snippet. then resize the window
<div id="homepage-carousel">
<img class="lazy_res" src="http://pre07.deviantart.net/338a/th/pre/i/2012/007/f/7/mapa_mundi_com_bandeiras___preto_by_plamber-d4leocd.jpg" alt="" />
<img class="lazy_res" src="http://img05.deviantart.net/a6be/i/2013/099/8/9/helena_harper_by_plamber-d6125tx.jpg">
</div>
&#13;
{{3}}