简体   繁体   English

使用jQuery,如何根据浏览器宽度添加和删除元素?

[英]Using jQuery, how do I add and remove elements based on browser width?

I'm working on something and I'm trying to add and remove elements based on the browser width. 我正在做一些事情,并且正在尝试根据浏览器的宽度添加和删除元素。 In the example that I have ( https://jsfiddle.net/swpm3aL1/ ), I want the image to appear when browser width is 700px or lower and remove the video, and vise versa. 在我的示例( https://jsfiddle.net/swpm3aL1/ )中,我希望在浏览器宽度为700px或更小时显示图像,并删除视频,反之亦然。

I have some code but it's not working. 我有一些代码,但是没有用。 What am I doing wrong? 我究竟做错了什么?

Thank you for your time and help! 感谢您的时间和帮助!

if ($(window).width() > 700) {
    $('body').remove('#image');
    $('body').add('#video');

} else {
    $('body').remove('#video');
    $('body').add('#image');
}

You clearly didn't RTFM 您显然不是RTFM

if ($(window).width() > 700) {
    $('#image').hide();
    $('#video').show();

} else {
    $('#image').show();
    $('#video').hide();
}

The jQuery manual, or the jsFiddle manual https://jsfiddle.net/swpm3aL1/1/ jQuery手册或jsFiddle手册https://jsfiddle.net/swpm3aL1/1/

If you want this on window resize 如果要在窗口上调整大小

$(window).on('resize', function(){
    if ($(window).width() > 700) {
        $('#image').hide();
        $('#video').show();

    } else {
        $('#image').show();
        $('#video').hide();
    }
}).trigger('resize'); // <-- and trigger so it works on page load

If you want to handle onload, resize and change of orientation, then following code will be handy: 如果要处理加载,调整大小和更改方向,那么以下代码将很方便:

$(window).on("orientationchange load resize", function () {
  if ($(window).width() > 700) {
      $('#image').hide();
      $('#video').show();
  } else {
      $('#image').show();
      $('#video').hide();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM