调整窗口大小时轮播无法正常工作

时间:2015-05-11 12:24:42

标签: javascript jquery html css

我有一系列3个div以直线向左浮动。每个div是页面的宽度。 这是HTML结构;

<div class="Horizontal-Wrapper">
      <div class="Horizontal-Section">
        <div class="Project-Wrapper">
          <div class="Project-Box" id="PJB1"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
          <div class="Project-Box" id="PJB2"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
        </div>
       </div>
       <div class="Horizontal-Section">
        <div class="Project-Wrapper">
          <div class="Project-Box" id="PJB3"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
          <div class="Project-Box" id="PJB4"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
        </div>
       </div>
       <div class="Horizontal-Section">
        <div class="Project-Wrapper">
          <div class="Project-Box" id="PJB5"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
          <div class="Project-Box" id="PJB6"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>          
        </div>
       </div>        
     </div>

所以在按钮上单击它应该移动下一个div。我通过使用以下脚本完成了这项工作;

   var inner_width = $('body').innerWidth();
   $('#next').on('click', function () {
      $('.Horizontal-Section').animate({'left': 'inner_width' +'px'});
   });

我面临的问题是,当浏览器调整大小时,滚动会搞乱,因为我无法获得适当的页面宽度。

3 个答案:

答案 0 :(得分:2)

您需要在调整大小时更改inner_width并重新定位元素。

我假设.Horizo​​ntal-Section在CSS中设置了100%的宽度。

var inner_width = $('body').innerWidth();

$('#next').on('click', function () {
    $('.Horizontal-Section').animate({'left': inner_width +'px'});
});

$(window).resize(function () {
    inner_width = $('body').innerWidth();
    $('.Horizontal-Section').css({'left': inner_width +'px'});
});

答案 1 :(得分:1)

您可以将您的工作代码放在一个函数中,并在(document).ready();(window).resize();上调用该函数

结帐以下代码

<强> JS

<script>
 $(document).ready(func_name);
 $(window).resize(func_name);

 function func_name(){
  var inner_width = $('body').innerWidth();
   $('#next').on('click', function () {
      $('.Horizontal-Section').animate({'left': 'inner_width' +'px'});
   });
 }
</script>

答案 2 :(得分:1)

您的问题源于不会多次重新检查浏览器的宽度。它检查页面加载,然后将变量设置为。

试试这个:

var inner_width = $('body').innerWidth();
$(window).resize(function() {
  inner_width = $('body').innerWidth();
});