Heim  >  Artikel  >  Web-Frontend  >  JS 实现导航栏悬停效果(续2)_javascript技巧

JS 实现导航栏悬停效果(续2)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:21:311168Durchsuche

JS-实现导航栏悬停
JS-实现导航栏悬停(续)

用Jquery重新写完这个页面之后,发现原来的方法还有是有几个问题:

1.首先Js代码冗余,导航条上的Tab是用js实现跳转而不是超链接;

2.还有导航条本身用fixed定位,但没有被设置为水平居中,而是在JS中更改left值使其居中。

问题2就导致了,当浏览器窗口尺寸发生变化的时候,浏览器中的div的位置都发生了变化,也就导致了没法通过页面中的div动态的给已fixed定位的导航条来定位。

最终的代码更改如下:

test.html

复制代码 代码如下:








Test



1


2

3

4

5

6

7





test.js
复制代码 代码如下:

//记录导航条原来在页面上的位置
var naviga_offsetTop = 0;

//使导航条,悬停在顶部
function naviga_stay_top(){
//获取滚动距离
var scrollTop = $(document).scrollTop();
//如果向下滚动的距离大于原来导航栏离顶部的距离
//直接将导航栏固定到可视区顶部
if( scrollTop > naviga_offsetTop ){
$("#nav").css({"top": "0px"});
} else {
//如果向下滚动的距离小原来导航栏离顶部的距离,则重新计算导航栏的位置
$("#nav").css({"top": naviga_offsetTop - scrollTop + "px"});
}
}

function onload_function(){
//记录初始状态导航栏的高度
naviga_offsetTop = $("#nav").attr("offsetTop");

//绑定滚动和鼠标事件
$(window).bind("scroll", naviga_stay_top);
$(window).bind("mousewheel",naviga_stay_top);
$(document).bind("scroll", naviga_stay_top);
$(document).bind("mousewheel",naviga_stay_top);
}

$(document).ready( onload_function );

test.css:注意navigation类的样式
复制代码 代码如下:

div.main{
width: 800px;
background: #CCC;
margin: 10px auto 0;
position: relative;
}

div.content{
width: 800px;
height: 400px;
background: yellow;
margin: 10px auto 0;
}

div.navigation{
width: 800px;
height: 40px;
background: red;
margin: 0 auto;
top: 400px;
left:50%;
position: fixed;
margin-left:-400px;
}

div.tab{
width: 195px;
height: 40px;
background: blue;
float: left;
margin-left: 5px;
}

总结:

出现这个问题的原因还是CSS的布局定位不熟悉。

在这里没法通过:margin 0 auto;来设置导航条div水平居中,因为fixed定位的元素没法通过这种方式来定位。

通过margin 0 auto;来定位的元素不能为fixed定位,并且其父元素必须要有固定的宽度。

那么怎么使fixed定位的元素水平居中呢?

通过:left: 50%,将该元素的最左边与父元素宽的中点对其,然后通过marg-left: [该元素宽度的1/2]px;来将这个元素向左移动它的宽度的一般,从而使这个元素居中。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn