如何用JS做固定在网页中的导航条

JavaScript025

如何用JS做固定在网页中的导航条,第1张

使元素固定在网页中,不需要用到JS的,只需要用到CSS样式就可以了。

使用css 中的   position:fixed fixed是相对于浏览器的定位,设置了这个样式的元素将不会随页面滚动而改变位置,固定在屏幕中。

如 :

.classname {

position:fixed

left:0

top:0

z-index:9999

}

给你一个朴素版的导航(包含css和html2部分):

css.css文件

body{

font-size:12px

font-family:Arial,

Helvetica,

sans-serif

margin:0px

padding:0px

color:white

}

ul,li{

margin:0px

padding:0px

}

li{

display:inline

list-style:none

text-align:center

font-weight:bold

float:left

}

a:link{

color:#336601

text-align:center

text-decoration:none

float:left

width:100px

padding:3px

5px

0px

5px

}

a:visited{

color:#336601

text-align:center

text-decoration:none

float:left

padding:3px

5px

0px

5px

width:100px

}

a:hover{

color:white

float:left

padding-left:6px

text-align:center

width:100px

text-decoration:none

background-color:#539D26

}

a:active{

color:white

float:left

padding:3px

3px

0px

20px

width:100px

text-align:center

text-decoration:none

background-color:#539D26

}

#nav{

width:600px

height:30px

border-bottom:0px

padding:0px

5px

position:absolute

z-index:1

left:

198px

top:

25px

}

.list{

line-height:20px

text-align:left

padding:4px

font-weight:normal

}

.menu1{

width:120px

height:auto

margin:6px

4px

0px

0px

border:1px

solid

#9CDD75

background-color:#F1FBEC

color:#336601

padding:6px

0px

0px

cursor:pointer

overflow-y:hidden

filter:Alpha(opacity=70)

-moz-opacity:0.7

}

.menu2{

width:120px

height:18px

margin:6px

4px

0px

0px

background-color:#F5F5F5

color:#999999

border:1px

solid

#EEE8DD

padding:6px

0px

0px

0px

overflow-y:hidden

cursor:pointer

}

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="UTF-8">

<title></title>

<style type="text/css">

li {

display: inline-block

width: 100%

height: 30px

line-height: 30px

}

li:active, li:focus, .li-active {

background: #dddddd

color: red

}

</style>

<script type="text/javascript">

onload = function () {

function removeActiveClass(node) {

node.className = ''

}

document.querySelector('ul[id=test]').onclick = function (e) {

Array.prototype.forEach.call(document.querySelectorAll('ul[id=test] >li'), removeActiveClass)

var target = e.target

target.className = 'li-active'

}

}

</script>

</head>

<body>

<ul id="test">

<li>1111</li>

<li>2222</li>

<li>3333</li>

<li>4444</li>

</ul>

</body>

</html>