CSS: vị trí cố định trên trục x nhưng không phải là y?


104

Có cách nào để sửa một vị trí chỉ trên trục x không? Vì vậy, khi người dùng cuộn lên, thẻ div sẽ cuộn lên cùng với nó, nhưng không phải cạnh nhau?


3
Có ổn không, nếu tôi đưa ra giải pháp JS cho vấn đề này?
Starx

1
Bạn cần javascript để làm điều này.
LostLin

@Starx - nó không chỉ OK, nó bắt buộc phải có :-)
Pete Wilson

Gần đây, tôi đã trả lời một câu hỏi tương tự có thể đúng hơn về những gì bạn đang tìm kiếm: stackoverflow.com/questions/8673560/…
Wex

Tôi biết câu hỏi khá cũ của nó, nhưng bạn vẫn gặp vấn đề với câu hỏi này?
Starx

Câu trả lời:


58

Nó cũng là một kỹ thuật đơn giản bằng cách sử dụng script. Bạn cũng có thể kiểm tra một bản demo ở đây .

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;
}

Cập nhật Tín dụng: @ PierredeLESPINAY

Như đã nhận xét, để làm cho tập lệnh hỗ trợ các thay đổi trong css mà không cần phải mã hóa lại chúng trong tập lệnh. Bạn có thể sử dụng như sau.

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

Demo :)


@PeteWilson, Ok, hãy kiểm tra giải pháp này
Starx

2
Bạn nghĩ gì về việc nhận leftgiá trị ở đầu hàm như init_left = $('#header').position()['left']hoặc một cái gì đó tương tự?
Pierre de LESPINAY,

@PierredeLESPINAY, Vâng, điểm rất tốt. Điều đó sẽ làm cho nó đủ linh hoạt để hỗ trợ các thay đổi.
Starx

2
Tôi thích giải pháp này và chỉ sử dụng nó cho chính mình. Một vấn đề mà tôi gặp phải với nó là các bản làm mới hơi bị giật khi bạn thực hiện thao tác cuộn trơn tru (ví dụ: bằng cách kéo thanh cuộn). Có vẻ như làm mới javascript chậm hơn làm mới css. Bất kỳ giải pháp cho điều này?
jsarma

17

Đây là một chủ đề cũ nhưng CSS3 có một giải pháp.

position: sticky;

Hãy xem bài đăng trên blog này.

Trình diễn:

css vị trí hoạt ảnh dính

Và tài liệu này.


1
Đã dành nhiều thời gian để tìm giải pháp cho điều này, câu trả lời của bạn phù hợp với nhu cầu của tôi một cách lý tưởng.
Christopher Shaw

6
Điều này là tốt cho nội dung dọc, nhưng không hiệu quả với cuộn ngang.
Cullub

10
Điều này không trả lời câu hỏi nào cả.
Alohci

12

Nếu khối của bạn ban đầu được định vị là tĩnh, bạn có thể muốn thử điều này

$(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>


8

Không, không thể với CSS thuần túy. Kiểu định vị đó sẽ cố định phần tử trong khung nhìn. Tôi đề nghị chỉ cần sửa phần tử ở một trong các cạnh của khung nhìn (tức là trên cùng, dưới cùng, trái hoặc phải) để nó không ảnh hưởng đến nội dung khác.


7

Bây giờ thiết bị di động chiếm hơn 70% thị trường internet, bạn có thể tạo ra thứ gì đó thông minh và nhạy bén để làm điều đó.

Bạn có thể tạo điều này rất dễ dàng chỉ với css, sử dụng tràn-x: cuộn cho một vùng chứa và tràn-y: cuộn cho một vùng chứa khác. Bạn có thể dễ dàng định vị các phần tử container với chiều rộng: 100vw và chiều cao: 100vh.

Nhấp chuột giữa vào ví dụ để kiểm tra nó. Hoạt động tốt nhất trên thiết bị di động vì bạn không nhìn thấy các thanh cuộn.

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>


Tôi không thích thanh cuộn dưới cùng chỉ hiển thị khi cuộn đến chân ...
Fanky

Trên trình duyệt di động, nó sẽ không xuất hiện. Trên Chrome, bạn có thể ẩn nó bằng CSS này .yourclass::-webkit-scrollbar-track, .yourclass::-webkit-scrollbar-thumb {display:none;}. Trên Firefox, bạn có thể ẩn nó bằng cách đặt nó bên ngoài một vùng overflow:hiddenchứa. Nhưng đó là một câu hỏi khác đã được trả lời trước đây, tôi chắc chắn về điều đó.
EPurpl3

2

Giải pháp của Starx cực kỳ hữu ích đối với tôi. Nhưng tôi đã gặp một số vấn đề khi cố gắng triển khai thanh bên cuộn dọc với nó. Đây là mã ban đầu của tôi, dựa trên những gì Starx đã viết:

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

Nó hơi khác so với giải pháp của Starx, vì tôi nghĩ mã của anh ấy được thiết kế để cho phép menu nổi theo chiều ngang thay vì chiều dọc. Nhưng đó chỉ là một bên. Vấn đề mà tôi gặp phải với đoạn mã trên là trong nhiều trình duyệt, hoặc tùy thuộc vào tải tài nguyên của máy tính, các chuyển động của menu sẽ bị sai lệch, trong khi giải pháp css ban đầu thì tốt và mượt mà. Tôi quy điều này là do các trình duyệt kích hoạt các sự kiện javascript chậm hơn so với việc triển khai css.

Giải pháp thay thế của tôi cho vấn đề này là đặt khung thành cố định thay vì tuyệt đối, sau đó hủy các chuyển động ngang bằng phương pháp của starx.

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

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

Bạn có thể nói rằng tất cả những gì tôi đang làm là giao dịch cho bất kỳ cuộn dọc cho bất kỳ cuộn ngang. Nhưng vấn đề là, 99% thao tác cuộn là theo chiều dọc và sẽ khó chịu hơn nhiều khi điều đó bị ngắt quãng so với khi cuộn theo chiều ngang.

Đây là bài đăng liên quan của tôi về vấn đề này, nếu tôi chưa hết kiên nhẫn của mọi người: Sửa menu theo một hướng trong jquery


2

Tôi tình cờ trong bài đăng này để tìm một cách hay để giữ tiêu đề / thanh điều hướng của tôi ở giữa và phản hồi với các thay đổi về kích thước.

//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)
  }
})

Khi chúng ta cuộn, thanh sẽ di chuyển lên trên khỏi màn hình. Nếu bạn cuộn sang trái / phải, nó sẽ cố định.


Cảm ơn anh trai. Điều này đã hiệu quả. Thật đơn giản !! Genius you
Ram

0

Tôi nhận ra rằng chủ đề này khá cũ nhưng nó đã giúp tôi đưa ra giải pháp cho dự án của mình.

Trong trường hợp của tôi, tôi có một tiêu đề mà tôi muốn không bao giờ rộng dưới 1000px, tiêu đề luôn ở trên cùng, với nội dung có thể đi không giới hạn.

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', '');
        }
    });

Điều này cũng sẽ xử lý khi trình duyệt của bạn nhỏ hơn chiều rộng tối thiểu của tiêu đề


0

Tôi chỉ thêm vị trí: tuyệt đối và điều đó đã giải quyết được vấn đề của tôi.


8
Định vị tuyệt đối cố định các phần tử liên quan đến tài liệu. Định vị cố định sẽ sửa chúng so với cửa sổ. Nếu sử dụng tuyệt đối giải quyết được vấn đề của bạn thì bạn đã không gặp phải vấn đề tương tự như câu hỏi này để bắt đầu.
Niall

0

Đây là một chủ đề rất cũ, nhưng tôi đã tìm thấy một giải pháp CSS thuần túy cho việc này bằng cách sử dụng một số lồng ghép sáng tạo. Tôi không phải là một fan hâm mộ của phương thức jQuery ...

Fiddle tại đây: 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;
}

6
Tuy nhiên, giải pháp của bạn yêu cầu cuộn div vùng chứa của nội dung thay vì cửa sổ thực tế, điều này không lý tưởng lắm - fiddle của bạn giải thích lý do. Nội dung của bạn đang chạy ra khỏi phía bên phải của trang, nhưng thanh cuộn ngang không có trên màn hình. Đó là một vấn đề lớn về khả năng sử dụng.
Niall

0

Đã cập nhật tập lệnh để kiểm tra vị trí bắt đầu:

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

Trên div mẹ, bạn có thể thêm

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
    });
});

Cảm ơn


0

Có, Bạn thực sự có thể làm điều đó chỉ bằng cách sử dụng CSS ...

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

Hãy cho tôi biết nếu nó hoạt động


-1

Giải pháp rất dễ dàng là:

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

bạn nên sử dụng CSS3 position:fixedcho điều này thay vì đi cho giải pháp js
Muhammad Aslam Omer

-3

Có vẻ như bạn cần sử dụng vị trí: cố định và sau đó đặt vị trí trên cùng thành phần trăm và vị trí bên trái hoặc bên phải thành một đơn vị cố định.

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.