即使屏幕扩展超过初始全宽,也可以划宽100%

时间:2016-02-17 09:15:18

标签: jquery html css

我有以下代码。最初会有一个标题分区,其宽度将设置为100%。但是当添加一些新的绝对div时,它位于屏幕的整个宽度之外(使得水平滚动被启用),标题的宽度将不是100%(因为已添加新空间)

请查看以下代码,我已经模拟了问题。

我希望标题的宽度与屏幕相同,与我看到的部分无关。我尝试使用vw代替%,但没有成功。

有没有办法在css中做到这一点?

或者每次使用jquery时是否需要动态更改宽度?



$(document).ready(function() {

  $("#btn").click(function() {


    $("#sample").toggle().css({
      top: 100,
      right: -110
    })
  });
})

body {
  margin: 0;
  padding: 0;
}
#header {
  width: 100%;
  height: 100px;
  background: #ccc;
}
#sample {
  width: 300px;
  height: 200px;
  background: #444;
  display: none;
  position: absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
</div>

<div id="sample">
</div>

<button id="btn">Click here</button>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

JS的一点点补充。它保留标题position: static(不固定),因为原始数据没有变化。

&#13;
&#13;
$(function(){
  $("#btn").click(function() {
    $("#sample").toggle().css({
      top: 100,
      right: -110
    })
    var clicks = $(this).data("clicks")
    var w = $("#header").width()
    if(clicks){ 
      $("#header").css("width", w - 110)

    }else{
      $("#header").css("width", w + 110)

    }
    $(this).data("clicks", !clicks);

  });
})
&#13;
body {
  margin: 0;
  padding: 0;
}
#header {
  width: 100%;
  height: 100px;
  background: #ccc;
}
#sample {
  width: 300px;
  height: 200px;
  background: #444;
  display: none;
  position: absolute;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myClass">This is clickable</div>
<div id="header">
</div>

<div id="sample">
</div>

<button id="btn">Click here</button>
&#13;
&#13;
&#13;

Info about the use of data用于切换点击次数

答案 1 :(得分:1)

$(document).ready(function() {

  $("#btn").click(function() {


    $("#sample").toggle().css({
      top: 100,
      right: -110
    })
  });
})
body {
  margin: 0;
  padding: 0;
  padding-top: 100px;
}
#header {
  width: 100%;
  height: 100px;
  background: #ccc;
  position: fixed;
  top: 0px;
}
#sample {
  width: 300px;
  height: 200px;
  background: #444;
  display: none;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
</div>

<div id="sample">
</div>

<button id="btn">Click here</button>