怎么让DIV固定在页面的某个位置而不随着滚动条随意滚动?

如题所述

可用的方法比较多,比较常见的是使用CSS。

1、使用CSS

CSS让DIV固定位置不随滚动条而滚动, fixed元素的绝对位置是相对于HTML元素来说,滚动条是body元素的。

(1)我们需要做的是,让body保持其原有高度,让html只有一个窗口那么高。代码我们可以这样写:

html{overflow:hidden;} 
body{height:100%;overflow:auto;}    

(2)我们可以利用绝对定位来定位我们想要固定在窗口某个位置的模块。假设我们要固定的内容在右上。

html{overflow:hidden;}
body{height:100%;overflow:auto;}
#rightform form{position:absolute;right:30px;top50px;}    

(3)页面由左侧菜单和右侧主体内容构成,右侧内容可能会很多,会出现翻屏。现在是要无论页面怎么翻屏滚动,左侧的菜单始终在左侧。请看CSS解决方案。

#site_nav{position:fixed; width:160px; padding:6px 10px; height:100%;  
background:#ffc; overflow-y:auto;} 
#content{padding:10px 10px 10px 190px;}

(4)我设置左侧div#site_nav的样式,将其位置固定,即position:fixed,并且设置固定宽度,高度为100%,为了区分右侧内容,我设置了背景颜色background:#ffc。

接着,我将内容部分div#content设置其padding值,注意关键是padding-left:190px,只有大于左侧菜单宽度的padding值,才能使右侧主体内容部分不会与左侧菜单重叠。

2、不使用JS:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

<style type="text/css">

ul{

margin:0;

padding:0;}

li{

list-style-type:none; float:left; margin-left:10px; line-height:30px;}

</style>

</head>

<body>

<div style="width:100%; height:30px; background-color:#093; position:fixed;left:0px; top:0px;">

<ul>

<li>sd</li>

<li>dsda</li>

<li>dsa</li>

</ul>

</div>

<div style="height:10000px; border:1px solid red;"></div>

<div style="width:100%; height:30px; background-color:#093; position:fixed;left:0px; bottom:0;"></div>

</body>

</html>

3、<html>
<head>
<title></title>
<style type="text/css">

html,body {
overflow:hidden;
margin:0px;
width:100%;
height:100%;
}

.virtual_body {
width:100%;
height:100%;
overflow-y:scroll;
overflow-x:auto;
}

.fixed_div {
position:absolute;
z-index:2008;
bottom:20px;
left:40px;
width:800px;
height:40px;
border:1px solid red;
background:#e5e5e5;
}
</style>
</head>

<body>
<div class="fixed_div">I am still here!</div>
<div class="virtual_body">
<div style="height:888px;">
I am content !
</div>
</div>

分析:

1、html,body:将默认可能会随机出现的滚动条,完全地隐藏了,这样不管您放了啥内容,它们都不会出来了。

2、.virtual_body:顾名思义,就是一个假的body了,它被设置为长宽都为100%的,意思就是它利用了所有可视的浏览器窗体显示所有的内容,并垂直允许出现滚动条。

3、.fixed_div:这下它可以利用绝对值进行定位了,因为在这个场景下,这个页面100%地被那个假冒的body给独霸了,而滚动条反正也出不来,您就可以自认为是在某个点蹲坑了,绝对安全。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-12-30
吧一个内容固定到某一个位置 ,相对与浏览器窗口进行定位就可以了。
定位 position 通常有 absolute 绝对定位,relative 相对定位,这个都是相对于body里面的块元素来说的,但是如果说想要吧某一个内容就国定在某一个位置,无论滚动条滑到哪里,他依然在浏览器窗口这个位置,就需要用到fixed了 。
fixed 元素框的表现类似于将 position 设置为 absolute,不过其包含块是视窗本身。同意具有 left 、 top、right、bottom 的值 他的用法和 absolute 类似
详情可以参考一下 W3C 里面的 解释。
第2个回答  2016-11-21

设置div为固定位置。如:

<div style="width:100px; height:100px; border:1px solid red; position:fixed; left:300px; top:300px;"></div>

这样就会固定在left:300px;top:300px;的位置,不会随着滚动条的滚动而滚动

第3个回答  2015-09-28
给div 加固定定位,比如你要固定到右下角:
div{position:fixed; right:20px; bottom:20px;}
相似回答