根据宽度隐藏元素

hide element based on width

如果图像大小 <= 300

,我想隐藏带有 class="wp-caption-text" 的元素
<div id="attachment_65209" style="width: 230px">
 <a href="#" rel="lightbox[70848]">
  <img src="/LCP-2015-05-31-s1.jpg" width="220" height="269">
 </a>
 <p class="wp-caption-text">Sen. Charles Schwertner • District 5</p>
</div>

到目前为止,我尝试使用以下方法但没有成功:

<script>
jQuery(window).on('resize load', function () {
 jQuery('.wp-caption-text').each(function(i, el){
  var section = jQuery('.wp-caption-text');
  var width = section.width();
  if (width <= 300) {
   section.attr('class', 'caption-none');
  }
 })
})
</script>
<style>.caption-none{display:none;}</style>

有什么建议吗?

试试这个:

jQuery('.wp-caption-text').each(function(i, el){
    if (jQuery(this).width() <= 300) {
        jQuery(this).addClass('caption-none');
    }
});

您可以使用.filter()过滤掉元素,然后使用addClass()添加class

jQuery(window).on('resize load', function() {

    //Filter elements having width < 300
    jQuery('.wp-caption-text').filter(function(i, el) {
        return $(this).width() <= 300;
    }).addClass('caption-none'); //Add the required class
})

您正在获取元素数组的宽度。您需要将它应用于每个:

var section = jQuery(this);
var width = section.width();