jQuery根据屏幕大小移动元素

时间:2015-07-28 13:37:34

标签: jquery

我正在寻找一种更好的解决方案,根据屏幕尺寸移动几个元素。我以为我的代码还可以。当我在桌面上调整浏览器窗口大小时,它工作得很好,但是当我在像移动电话这样的小设备上测试时,该元素没有移动,因为没有调整大小事件。

然后我在文档就绪行之后测试了这段代码,但它根本不起作用:

var window-width = $(window).width();

if(window-width < 800) {

    $( ".intro-content p" ).prependTo( ".intro-bottom" );
    $( ".intro-content h1" ).prependTo( ".intro-bottom" );

}

这是我寻求改进解决方案的第一个代码:

$(window).resize(function() {
    var win = $(window).width();
responsiveAction(win);
});

function responsiveAction(width) {

if(width < 800) {

    $( ".intro-content p" ).prependTo( ".intro-bottom" );
    $( ".intro-content h1" ).prependTo( ".intro-bottom" );

}

if(width > 800) {

    $( ".intro-bottom h1" ).appendTo( ".intro-content" );
    $( ".intro-bottom p" ).appendTo( ".intro-content" );
}

}

3 个答案:

答案 0 :(得分:1)

我有一个替代方案:将元素放在标记中的两个位置,然后使用CSS media queries在相关位置显示/隐藏它。看,妈,没有JavaScript!

if (!mysql_query($sql)) {
   echo mysql_error();
}
@media (max-width: 600px) {
  /* Smaller screen, hide location 2 */
  .location2 {
    display: none;
  }
}
@media (min-width: 601px) {
  /* Larger screen, hide location 1 */
  .location1 {
    display: none;
  }
}

来自你的评论:

  

我不想两次写标题和文字,或者我只需要编写一次然后使用jQuery

假设您写了一次,然后在加载页面时(您已使用<div class="target location1">I'm in location 1, I'll disappear if the viewing area is &gt; 600px wide</div> <div>...stuff here...</div> <div>...stuff here...</div> <div>...stuff here...</div> <div>...stuff here...</div> <div>...stuff here...</div> <div class="target location2">I'm in location 2, I'll disappear if the viewing area is &lt;= 600px wide</div>,这没关系;我只是确保ready标记位于页面末尾相反),只需复制一次内容:

script

然后将媒体查询应用于$(function() { setup(".intro-content p"); setup(".intro-content h1"); function setup(selector) { var content = $(selector); content.clone().addClass("bottom").prependTo(".intro-bottom"); content.addClass("content"); } }); .content

答案 1 :(得分:0)

我使用此解决方案并且效果很好

address="http://127.0.0.1:4873/_session"
cred="{\"name\":\"some\", \"password\":\"thing\"}"    
temp="curl -v -s -X POST $address -d $cred"
echo $temp

答案 2 :(得分:0)

我使用此解决方案并且效果很好

$(document).ready(function () {
    moveButtons();
});

 $(window).resize(function() {
    moveButtons();
});

 function moveButtons() {
    var win = $(window).width();
    if (win > 800) {
        $('#positionTop').append($('#myContent'));  // move to div with id positionTop
    } else {
        $('#positionDown').append($('#myContent'));  // move to div with id positionDown
    }
};
相关问题