根据视口宽度加载jQuery

时间:2014-06-12 19:51:00

标签: jquery function resize viewport

我有一个活动日历,显示最上一行中的所有星期几。日历本身具有响应性,但当它为移动设备缩小时,一周中的日子会延伸到它们的盒子之外,并且彼此重叠 - 这也会产生一些宽度溢出。

我想在移动设备上查看时使用jQuery将“Sunday”更改为“S”,但我不知道该怎么做。

使用“.replaceWith”命令,我设法让它的一部分工作。我根本无法弄清楚如何根据浏览器宽度触发此脚本。

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

$(window).resize(function() {
    if ($(window).width() < 950) {
        $( "div.sunday" ).replaceWith( "S" );
        $( "div.monday" ).replaceWith( "M" );
        $( "div.tuesday" ).replaceWith( "T" );
        $( "div.wednesday" ).replaceWith( "W" );
        $( "div.thursday" ).replaceWith( "T" );
        $( "div.friday" ).replaceWith( "F" );
        $( "div.saturday" ).replaceWith( "S" );
    }
}

这是小提琴:http://jsfiddle.net/CN8Gs/1/

2 个答案:

答案 0 :(得分:4)

试试这个:

$(window).resize(function() {
console.log($(window).width());
if ($(window).width() < 950) {
    $( "div.sunday" ).text( "S" );
    $( "div.monday" ).text( "M" );
    $( "div.tuesday" ).text( "T" );
    $( "div.wednesday" ).text( "W" );
    $( "div.thursday" ).text( "T" );
    $( "div.friday" ).text( "F" );
    $( "div.saturday" ).text( "S" );
}
else
{
    $( "div.sunday" ).text( "Sunday" );
    $( "div.monday" ).text( "Monday" );
    $( "div.tuesday" ).text( "Tuesday" );
    $( "div.wednesday" ).text( "Wednesday" );
    $( "div.thursday" ).text( "Thursday" );
    $( "div.friday" ).text( "Friday" );
    $( "div.saturday" ).text( "Saturday" );
 }
});
$(window).trigger('resize');

JSFiddle demo

答案 1 :(得分:1)

这将有两种方式:Fiddle sample here...(运行并调整结果窗口大小。实际上950很宽。您可能希望减小宽度以进行更真实的测试。)

$(window).resize(function() {
    if ($(window).width() < 950) {
        $( "div.sunday" ).html("S");
        $( "div.monday" ).html( "M" );
        $( "div.tuesday" ).html( "T" );
        $( "div.wednesday" ).html( "W" );
        $( "div.thursday" ).html( "T" );
        $( "div.friday" ).html( "F" );
        $( "div.saturday" ).html( "S" );
    } else {
        $( "div.sunday" ).html("Sunday");
        $( "div.monday" ).html( "Monday" );
        $( "div.tuesday" ).html( "Tuesday" );
        $( "div.wednesday" ).html( "Wednesday" );
        $( "div.thursday" ).html( "Thursday" );
        $( "div.friday" ).html( "Friday" );
        $( "div.saturday" ).html( "Saturday" );    
    }
});