我有以下代码。最初会有一个标题分区,其宽度将设置为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;
答案 0 :(得分:1)
JS的一点点补充。它保留标题position: static
(不固定),因为原始数据没有变化。
$(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;
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>