jQuery:根据屏幕宽度更改元素位置

时间:2016-02-16 10:17:42

标签: jquery html css

当我调整屏幕大小时,如何实时更改元素位置?

例如,如果屏幕最初是> 500px元素应位于x位置,否则如果我调整屏幕大小并使其变小,则应重新定位元素。必须在不按下按钮的情况下进行此操作。

jsfiddle:https://jsfiddle.net/zjgrmf24/2/

HTML:

<body>
 <div class="change_offset">
   reposition
 </div>
 <div class="here">
   move here
 </div>
</body>

CSS:

.here {
  margin-top:200px;
  margin-left:100px;
}
.change_position {
  position: absolute;
}

JS:

$(document).ready(function(){
  herePos = $('.here').offset();
  change = $('change_offset');

  if($('body').width() < 500)
  {
    change.css({
        left: herePos.left + "px",
      top: herePos.top + "px"
    })
  }
  else
  {
    change.css({
        left: 'auto',
      top: 'auto'
    })
  }
})

2 个答案:

答案 0 :(得分:1)

使用chart1.ChartAreas[0].AxisX.Minimum = 0.7; 事件:

resize

注意:您的代码正在成为The Horror of Implicit Globals的牺牲品。声明你的变量。

答案 1 :(得分:0)

请参阅此处https://jsfiddle.net/zjgrmf24/5/

我认识到的第一件事是你没有使用正确的选择器。 另外你也应该使用窗口调整大小。

var resize = function() {
  herePos = $('.here').offset();
  change = $('.change_position');

  if($('body').width() < 500)
  {
    change.css({
        left: herePos.left + "px",
      top: herePos.top + "px"
    })
  }
  else
  {
    change.css({
        left: 'auto',
      top: 'auto'
    })
  }
}

$(document).ready(resize);
$(window).on('resize', resize);