CSS:在x轴上固定位置但在y轴上不固定?

问题描述 投票:0回答:18

有没有办法只固定x轴上的位置?那么当用户向上滚动时,div 标签会随之向上滚动,但不会左右滚动?

css
18个回答
61
投票

这也是使用脚本的简单技术。您也可以在此处查看演示。

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

CSS

#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

更新信用:@PierredeLESPINAY

如评论所述,使脚本支持 css 中的更改,而无需在脚本中重新编码。您可以使用以下内容。

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

演示:)


19
投票

这是一个旧线程,但 CSS3 有一个解决方案。

position: sticky;

看看这篇博文。

演示:

还有这个文档。


14
投票

如果您的块最初定位为静态,您可能想尝试这个

$(window).on('scroll', function () {

  var $w = $(window);
  $('.position-fixed-x').css('left', $w.scrollLeft());
  $('.position-fixed-y').css('top', $w.scrollTop());

});
.container {
  width: 1000px;
}

.position-fixed-x {
  position: relative; 
}

.position-fixed-y {
  position: relative;
}

.blue-box {
  background:blue;
  width: 50px;
  height: 50px;
}

.red-box {
  background: red;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="position-fixed-y red-box">
  
</div>

The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do.

<div class="position-fixed-x blue-box">
  
</div>

DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA.

The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring.
  
 The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer.
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism).
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein.
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created.
</div>


9
投票

现在移动设备占互联网市场的份额超过 70%,您可以创建一些智能且响应迅速的东西来实现这一点。

您可以仅使用 css 轻松创建此内容,对容器使用溢出 x:scroll,对另一个容器使用溢出 y:scroll。您可以轻松定位宽度:100vw 和高度:100vh 的容器元素。

中键单击示例进行测试。在移动设备上效果最好,因为您看不到滚动条。

body{max-width:100%}
*{box-sizing:border-box;}
.container{background:#ddd;overflow-y:scroll;width:500px;max-height:100vh;}
.header{background: pink;}
.body{background: teal;padding:20px;min-width: 100%;overflow:scroll;overflow-y:hidden;min-height:300px;}
.body >div{min-width:800px;}
<body>
  <div class="container">
    <div class="header">
       Button 1 > Button 2 > Button 3
    </div>
    <div class="body">
      <div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
     </div>
    </div>
  </div>
</body>


8
投票

不,纯 CSS 是不可能的。这种定位将元素固定在视口中。我建议简单地将元素固定到视口的一侧(即顶部、底部、左侧或右侧),这样它就不会干扰其他内容。


2
投票

Starx 的解决方案对我非常有帮助。但是当我尝试用它实现垂直滚动侧边栏时遇到了一些问题。这是我的初始代码,基于 Starx 所写的:

function fix_vertical_scroll(id) {
    $(window).scroll(function(){
        $(id).css({
            'top': $(this).scrollTop() //Use it later
        });
    });
}

这与 Starx 的解决方案略有不同,因为我认为他的代码旨在允许菜单水平浮动而不是垂直浮动。但这只是一个旁白。我在上面的代码中遇到的问题是,在很多浏览器中,或者根据计算机的资源负载,菜单移动会不稳定,而最初的 css 解决方案则很好且流畅。我将此归因于浏览器触发 javascript 事件的速度比实现 css 的速度慢。

我对这个不稳定问题的替代解决方案是将框架设置为固定而不是绝对,然后使用starx的方法取消水平运动。

function float_horizontal_scroll(id) {
    jQuery(window).scroll(function(){
        jQuery(id).css({
            'left': 0 - jQuery(this).scrollLeft()
        });
    });
}

#leftframe {
 position:fixed;
 width: 200;
}   

你可能会说我所做的只是用垂直滚动的不稳定性来换取水平滚动的不稳定性。但问题是,99% 的滚动都是垂直的,当垂直滚动时,它比水平滚动时更烦人。

这是我关于此事的相关帖子,如果我还没有耗尽大家的耐心的话:Fishing a menu in one Direction in jquery


2
投票

我偶然发现这篇文章,寻找一种好方法来保持标题/导航栏居中并响应大小变化。

//CSS
.nav-container {
  height: 60px;  /*The static height*/
  width: 100%;  /*Makes it responsive to resizing the browser*/
  position: fixed;  /*So that it will always be in the center*/
}

//jQuery
$(window).scroll(() => {
  if ($(document).scrollTop() < 60) {
    $('.nav-container').css('top', $(document).scrollTop() * -1)
  }
})

当我们滚动时,该栏会向上移动离开屏幕。如果您向左/向右滚动,它将保持固定。


0
投票

我意识到这个线程非常旧,但它帮助我为我的项目找到了解决方案。

就我而言,我希望标题的宽度永远不会小于 1000 像素,标题始终位于顶部,内容可以不受限制。

header{position:fixed; min-width:1024px;}
<header data-min-width="1024"></header>

    $(window).on('scroll resize', function () {
        var header = $('header');
        if ($(this).width() < header.data('min-width')) {
            header.css('left', -$(this).scrollLeft());
        } else {
            header.css('left', '');
        }
    });

当您的浏览器小于标题最小宽度时,这也应该处理


0
投票

这是一个非常古老的线程,但我使用一些创造性的嵌套找到了一个纯 CSS 解决方案。我根本不喜欢 jQuery 方法...

在这里摆弄: https://jsfiddle.net/4jeuv5jq/

<div id="wrapper">
    <div id="fixeditem">
        Haha, I am a header. Nah.. Nah na na na
    </div>
    <div id="contentwrapper">
        <div id="content">
            Lorem ipsum.....
        </div>
    </div>
</div>

#wrapper {
position: relative;
width: 100%;
overflow: scroll;
}

#fixeditem {
position: absolute;
}

#contentwrapper {
width: 100%;
overflow: scroll;
}

#content {
width: 1000px;
height: 2000px;
}

0
投票

更新了脚本以检查起始位置:

function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
    var leftScroll = jQuery(this).scrollLeft();
    if (isLeft)
        el.css({ 'left': (start + leftScroll) + 'px' });
    else
        el.css({ 'right': (start - leftScroll) + 'px' });
});

}


0
投票

例如,如果您想将其固定在右侧,请使用

justify-content: flex-end

更多:http://www.w3schools.com/cssref/css3_pr_justify-content.asp


0
投票

在父div上您可以添加

overflow-y: scroll; 
overflow-x: hidden;

0
投票
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

谢谢


0
投票

是的,实际上你只能通过使用 CSS 来做到这一点...

body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }

告诉我是否有效


0
投票

您现在可以使用

position: sticky
在 CSS 中本地执行此操作。例如,要在水平滚动时将元素粘贴到左侧,您可以使用

.my-sticky-element {
    position: sticky;
    left: 0px;
}

通过设置

top
bottom
left
right
,您可以控制元素的粘贴位置。请注意,它将坚持到具有滚动机制的最近的祖先。

更多信息请访问 https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky


-1
投票

我刚刚添加了position:absolute,这解决了我的问题。


-1
投票

非常简单的解决方案是:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}

-3
投票

听起来你需要使用position:fixed,然后将顶部位置设置为百分比,将左侧或右侧位置设置为固定单位。

© www.soinside.com 2019 - 2024. All rights reserved.