根据窗口大小有条件地加载一些html [英] conditionally load some html based on window size

查看:66
本文介绍了根据窗口大小有条件地加载一些html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加载地图,但是我只想假设它们在wifi上就可以加载地图.由于没有真正的方法来执行此操作,因此我仅假设如果窗口宽度大于600,则为.加载iframe有点棘手-但是仅加载图像会让我起步.这行得通,但是如果我在那儿推了一堆复杂的html似乎就行不通了.无论如何,我不确定我是否应该在html的中间放置脚本.

I want to load a map, but I only want to load it if I can assume that they are on wifi. Since there is no real way to do this, I'm going to just assume that if the window width is larger then 600, that they are. Loading the iframe is a little more tricky - but just loading an image would get me started. This works, but It doesn't seem to work if I shove a bunch of complicated html in there. I'm not really sure that I should have scripts in the middle of my html anyways.

<script>
  if (document.documentElement.clientWidth > 600) {
    document.write("<h1>Hello</h1>");
  }
</script>

我认为此文章会对我有所帮助,但是有点烦我.

I thought this THIS ARTICLE would help me, but it is a little over my head.

有人对我有一些提示或帮助吗?

Does anyone have some tips or some reading for me?

谢谢.

也许我应该拥有一个永恒的.html文件并将其拉入...?

maybe I should have an eternal .html file and pull that in... ?

转义和填充存在问题-嵌入代码中有大量疯狂的字符等...

There are problems with escaping and stuff - when there are tons of crazy characters in embed codes etc...

推荐答案

您永远不要使用document.write(),这不是一个好习惯.相反,您可以使用javascript的.innerHTML或jQuery的.html(). jQuery还有其他几种方法可以执行此类工作,例如.append().appendTo().prepend().prependTo():

You should never use document.write() it not a good practice to use it. Instead you can use .innerHTML of javascript or .html() of jQuery. jQuery has several other methods doing this kind of work like .append(), .appendTo() similarly .prepend(), .prependTo():

$(function () {
   var width = $(window).width();
   if (width <= 600) {
      $('<p>lesser than 600</p>').appendTo('body');
   } else {
      $('<p>greater than 600</p>').appendTo('body');
   }
});

演示场

CSS媒体查询:

同样,您也可以使用CSS媒体查询来实现这种事情:

DEMO FIDDLE

CSS MEDIA QUERIES:

Also this kind of thing you can achieve with css media queries too:

span {
   color:green;
   font-weight:bold;
}
.div600 {
   display:none
}
.divOther {
   display:block
}
@media all and (max-width:600px) { /****<-----This media query******/
   .div600 {
       display:block
   }
   .divOther {
       display:none
   }
}    

这篇关于根据窗口大小有条件地加载一些html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆