【问题标题】:Avoid horizontal scrolling to position absolute div to the right with CSS使用 CSS 避免水平滚动以将绝对 div 定位到右侧
【发布时间】:2015-01-20 02:10:31
【问题描述】:
我正在放置一个具有 CSS 绝对位置的 div,隐藏在 HTML 文档的右侧并显示一个水平滚动,我可以避免这种情况吗?
这是一个例子:
http://jsfiddle.net/milindex/3pettu8m/1/
$("#open").click(function(e) {
e.preventDefault();
$("#menu").toggleClass("show");
});
#menu {
position: absolute;
background-color: #222;
z-index: 10;
width: 280px;
color: #bbb;
top: 0;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
transition: all 0.3s ease;
opacity: 1;
}
.right {
right: -280px;
}
.show {
right: 0;
}
#showmenu {
margin-left: 100%;
position: absolute;
top: 0;
padding: 6px 10px 7px 10px;
font-size: 1.3em;
color: #FFCC33;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
transition: all 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="open">Open Main</a>
<nav id="menu" class="menuUser right">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</nav>
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案2】:
只需将其添加到您的代码中
html {
overflow-x:hidden
}
这是一个sn-p:
$("#open").click(function(e){
e.preventDefault();
$("#menu").toggleClass("show");
});
html {
overflow-x:hidden
}
#menu {
position: absolute;
background-color: #222;
z-index: 10;
width: 280px;
color: #bbb;
top: 0;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
transition: all 0.3s ease;
opacity: 1;
}
.right { right: -280px; }
.show { right: 0; }
#showmenu {
margin-left: 100%;
position: absolute;
top: 0;
padding: 6px 10px 7px 10px;
font-size: 1.3em;
color: #FFCC33;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
transition: all 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href="#" id="open">Open Main</a>
<nav id="menu" class="menuUser right">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</nav>
【解决方案3】:
当然,您可以添加overflow:hidden,但我认为真正的答案是将right: 0; 添加到您的#menu。这会将您的 280px div 的右边缘放在页面的右边缘,不会溢出,因此不会滚动。
【解决方案4】:
$("#open").click(function(e){
e.preventDefault();
if($("#menu").hasClass('right')) {
$("#menu").removeClass('right');
$("#menu").addClass('show');
}else{
$("#menu").addClass('right');
$("#menu").removeClass('show');
}
});
这可以在不更改 CSS 的情况下解决您的问题。