Javascript 在顶部相对于div容器固定一个标题
我在固定顶部的收割台时遇到问题。标题在容器div中,我希望它保持在顶部,即使容器div被滚动 HTML:Javascript 在顶部相对于div容器固定一个标题,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我在固定顶部的收割台时遇到问题。标题在容器div中,我希望它保持在顶部,即使容器div被滚动 HTML: <div class="wrapper"> <div class="container"> <div class="fixed"> SHOULD BE FIXED </div> </div> </div> 这里有一个风格位置:固定的是一种方式: .
<div class="wrapper">
<div class="container">
<div class="fixed">
SHOULD BE FIXED
</div>
</div>
</div>
这里有一个风格
位置:固定的是一种方式:
.fixed {
position: fixed;
width: inherit;
}
演示:更改。固定类位置:绝对位置:固定并将宽度设置为300px!:)
CSS:
尝试使用jquery以获得更友好的交叉浏览方式
<script>
$(document).ready(function() {
var div = $('**.fixed**');
var start = $(div).offset().top;
$.event.add(window, "scroll", function() {
var ul = $(window).scrollTop();
$(div).css('position',((ul)>start) ? 'fixed' : '');
});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 2000);
return false;
}
}
});
</script>
$(文档).ready(函数(){
var div=$('**.fixed**');
var start=$(div).offset().top;
$.event.add(窗口,“滚动”,函数(){
var ul=$(window.scrollTop();
$(div).css('position',((ul)>start)?'fixed':'';
});
});
$('a[href*=#]:非([href=#])。单击(函数(){
if(location.pathname.replace(/^\/,“”)=此.pathname.replace(/^\/,“”)
||location.hostname==this.hostname){
var target=$(this.hash);
target=target.length?target:$('[name='+this.hash.slice(1)+']');
if(目标长度){
$('html,body')。设置动画({
scrollTop:target.offset().top
}, 2000);
返回false;
}
}
});
只需在之前或之后添加一些内容,就可以解决问题。我不知道width:inherit
,我正在尝试width:100%
,这导致固定div扩展到浏览器的宽度。顺便说一句:)@AamirAfridi为什么不将容器的宽度更改为30000px
?你的案例是一个完全不同的问题,情况不同。@RokoC.Buljan真棒的名字!然而,背后的代码并不性感,因为你必须使用JS,因为一旦你将一个元素设置为固定,它就变成了一个不值得触摸的便便,而是一根棍子(JavaStick:D),因为他们还没有发明一些更动态的CSS计算,比如calc(inherit-17px)实际上,这里我必须指定宽度,但我在设置中使用了100%,这使得固定div适合浏览器的宽度。如何限制它呢?所以试试宽度:inherit;roko,position:fixed在所有使用css的浏览器中都不兼容。他要求的这个固定标题比使用css更好。
.fixed{
background:#aaa;
position:fixed;
height:50px;
width:300px;
text-align:center;
font-weight:bold;
padding:15px 0;
box-sizing:border-box;
-moz-box-sizing: border-box;
}
<script>
$(document).ready(function() {
var div = $('**.fixed**');
var start = $(div).offset().top;
$.event.add(window, "scroll", function() {
var ul = $(window).scrollTop();
$(div).css('position',((ul)>start) ? 'fixed' : '');
});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 2000);
return false;
}
}
});
</script>