2016-06-29 40 views
0

如何在浏览器宽度调整大小时更改给定段落的内容?举例来说,在我的网站的移动版本,我想带班“主要铅”有以下内容的段落:如何根据视口宽度更改给定段落的内容(即动态内容替换)

<p class="main-lead">Some content goes here.</br>And some content goes here</p> 

现在,当有人观看来自平板电脑或笔记本电脑这个页面,我想本段内容进行更改,像这样:

<p class="main-lead">Previous content has been replaced.</p> 

我有点明白,我需要使用jQuery做,我试图写一个脚本来执行这个任务:

jQuery(window).resize(function() { 
    if ($(window).width() > 768) { 
     // if screen width is more than 768px 
     $(".main-lead").html('Previous content has been replaced.'); 
    } 
}); 

它似乎可行,但如果用户决定将屏幕重新调整回移动视图,内容将保持与平板电脑和桌面版本相同,而不是移动版本。

因此,我希望在浏览器窗口来回调整大小时,可以动态改变本段的内容。

任何建议将不胜感激。谢谢。

回答

5

你也可以尝试用CSS代码。

<style> 
.mobile { display:none; } 
@media screen and (max-width:768px) { 
.desktop { display:none; } 
.mobile { display:block; } 
} 
</style> 
<p class="main-lead"> 
    <span class="desktop">Some content goes here.</br>And some content goes here</span> 
    <span class="mobile">Previous content has been replaced.</span> 
</p> 
+1

我觉得这是最好尽可能 – user3154108

+0

啊,为什么我还没有想过用这样的想法与白手起家隐藏XS隐藏隐藏SM-MD等类一个js的解决方案。感谢您的建议。 –

+0

很好,如果你使用bootstrap框架,它是一个更好的主意。 – Nehemiah

0

var $window = $(window), 
 
    $mainLead = $(".main-lead"); // cacheing the main elements for reuse 
 

 
$window.resize(function() { 
 
    if ($window.width() > 768) { 
 
    // if screen width is more than 768px 
 
    $mainLead.html($mainLead.data('contentNotMobile')); 
 
    } else { 
 
    // if screen width is NOT more than 768px 
 
    $mainLead.html($mainLead.data('contentMobile')); 
 
    } 
 
}); 
 

 
$window.trigger('resize'); // fire the resize even on load to catch the initial state of the page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<p class="main-lead" data-content-mobile="Some content goes here.</br>And some content goes here" data-content-not-mobile="Previous content has been replaced.">Some content goes here.</br>And some content goes here</p>

你需要缓存(存储作为变量,数据属性,等等)使切换前的“原始”的内容。在我的示例中,我将这两个版本的内容存储为HTML data-attributes,以避免必须管理<p>的初始内容。请注意,您也必须“抓住”网页的初始状态。在完成侦听器设置后,完成$window.trigger('resize')

然后,它是作为与else时触发的$(window).width()不超过768大,恢复缓存的内容/串扩展现有if块一样简单。 jQuery's .data()是存储此类信息的一种便捷方式,但您可以通过其他方式来执行此操作。