根据屏幕大小替换HTML

我试图以小屏幕尺寸替换HTML内容,然后在窗口再次变大时替换它。 我的代码可以使用,但如何删除更改呢?

这是我到目前为止的代码:

$(window).resize(function() { if (window.innerWidth < 480) { $('.LatestNews').replaceWith('

News Link

'); } else if (window.innerWidth > 480) { // Change back to original .LatestNews } }).resize();

谢谢。

我建议看看responsejs.com 。 它提出了一些基于视口替换内容的好方法,是解决这个问题的优雅方案。

您要做的第一件事是定义断点。 这样的东西会起作用:

  (function() { Response.create({ mode: 'markup', prefix: 'r', breakpoints: [0,320,481,641,961,1020,1281] }); Response.create({ mode: 'src', prefix: 'src', breakpoints: [0,320,481,641,961,1020,1281] }); })(); 

接下来,您可以使用它的自定义数据属性将其放入标记中的内容中。 例如

 
This is your default content

这更具语义性,因为您可以在标记中使用这两个版本,而不是使用JS来创建它们。

有关详细信息,请参阅文档。

replaceWith函数正在改变DOM结构并替换组件中的任何内容; 因此它将不再了解之前的情况。

在执行替换之前,您可以在全局变量中捕获$(’。LatestNews’)的innerHTML内容,然后在屏幕resize时将其更改回来:

 var originalContent = ''; $(window).resize(function() { if (window.innerWidth < 480) { originalContent = $('.LatestNews').innerHTML; $('.LatestNews').replaceWith('

News Link

'); } else if (window.innerWidth > 480) { // Change back to original .LatestNews $('.LatestNews').innerHTML = originalContent; } }).resize();

注意这只有在您的页面上有1个.LatestNews实例时才有效; 如果你正在处理多个这将无法正常工作。

我会推荐这样的东西。

 //setup some variables. You only need to change the top two and this code should work on your site. var parentElem = $('div'), bigContent = "

this is some dummy content

", smallContent = parentElem.html(), s = 0; //call your function every time the browser is re-sized. The arguments are: 1. the parent of the content you want to change, 2. the original content, 3. the content you want to show on larger screens $(window).resize(function(){ replaceContent(parentElem, smallContent, bigContent); }); function replaceContent(parent, small, big){ // check if a breakpoint has been "crossed". I'm using the 's' variable to check if we have already run at this breakpoint to prevent needlessly repeating the function every time the user re-sizes. if (window.innerWidth < 481 && s === 1 ) { parent.children().remove(); parent.html(small); s = 0; } else if ( window.innerWidth > 480 && s === 0) { parent.children().remove(); parent.html(big); s = 1; }; }

这不是最好的事情。 可能结构更好,但它会完成这项工作。