Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Определение расстояние от края браузера и элемента (https://javascript.ru/forum/dom-window/83074-opredelenie-rasstoyanie-ot-kraya-brauzera-i-ehlementa.html)

Сергей Ракипов 07.09.2021 13:34

Определение расстояние от края браузера и элемента
 
Я помню что уже делал такой скрипт но не могу найти, пробую по памяти сделать все не работает.

Смысл в том что бы при достижение элемента определенного расстояние до края браузера сверху, ну что бы поменялся стиль. Вроде написал все правильно но не работает и даже нету ошибки.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        header{
            height: 200px;
        
        }
        footer{
            height: 1000px;
        }
        .blok{
            width: 80px;
            height: 80px;
            background-color:#000;
            background-image: url(https://rakipov.ru/files/tsifra1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
        .blok2{
            width: 80px;
            height: 80px;
            background-color:#000;
            background-image: url(https://rakipov.ru/files/icon1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
    </style>
</head>
<body>
    <header></header>
    <section>
        <div class="blok"></div>
    </section>
    <footer></footer>
    <script>
        const blok = document.querySelector(".blok");

        let anim1 = () => {
            let ikonka1 = tsifra1.getBoundingClientRect();
            if (ikonka1.top >= 100) {
                blok.classList.add("blok2");
            }
        };
        window.addEventListener("scroll", anim1);
    </script>
</body>
</html>

Сергей Ракипов 07.09.2021 14:06

Вспомнил еще вот тко вариант и тоже не сработало

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        header{
            height: 500px;
        
        }
        footer{
            height: 1500px;
        }
        .blok{
            width: 80px;
            height: 80px;
            background-color:#000;
            background-image: url(https://rakipov.ru/files/tsifra1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
        .blok2{
            width: 80px;
            height: 80px;
            background-color:#000;
            background-image: url(https://rakipov.ru/files/icon1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
    </style>
</head>
<body>
    <header></header>
    <section>
        <div class="blok"></div>
    </section>
    <footer></footer>
    <script>
        const blok = document.querySelector(".blok");

        let anim1 = () => {
            if (pos >= 100) {
                blok.style.backgroundImage = "url('https://rakipov.ru/files/icon1.svg')";
            }
            console.log(blok.offsetTop);
        };
        window.addEventListener("scroll", anim1);
    </script>
</body>
</html>

Aetae 07.09.2021 14:13

Код не глядел, мож потом, но сходу могу сказать, что сейчас такие задачи решаются через Intersection Observer.)

рони 07.09.2021 15:05

Цитата:

Сообщение от Сергей Ракипов
не работает

tsifra1 что это? строка 48 код 1

pos что это? строка 48 код 2

рони 07.09.2021 15:07

Сергей Ракипов,
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        header{
            height: 200px;

        }
        footer{
            height: 1000px;
        }
        .blok{
            width: 80px;
            height: 80px;
            background-color:#D3D3D3;
            background-image: url(https://rakipov.ru/files/tsifra1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
        .blok.blok2{
            width: 80px;
            height: 80px;
            background-color:#000;
            background-image: url(https://rakipov.ru/files/icon1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
    </style>
</head>
<body>
    <header></header>
    <section>
        <div class="blok"></div>
    </section>
    <footer></footer>
    <script>
        const blok = document.querySelector(".blok");

        let anim1 = () => {
            let ikonka1 = blok.getBoundingClientRect();
            blok.classList.toggle("blok2", ikonka1.top >= 100);
        };
        window.addEventListener("scroll", anim1);
        anim1(); 
    </script>
</body>
</html>

Сергей Ракипов 07.09.2021 17:06

рони,
Спасибо завтра сяду разбираться.

Aetae,
А этот способ чем лучше?

Сергей Ракипов 08.09.2021 09:25

рони,
Видимо к вечеру вчера устал и наделал кучу ошибок. Сейчас все понятно.
Вопрос а если мне нужно учитывать ширину браузера и в зависимости от ширины браузера делать другие значение от высоты экрана, к примеру top не 100 а 300 если ширина экрана 320

То мне нужно использовать window.innerwidth, но мне нужно это прямо в той функции писать или отдельно?

Сергей Ракипов 08.09.2021 09:27

Aetae,
Я прочитал о преимуществах, а есть какой то рабочий пример что бы так сказать разбираться методом тыка, мне сложно в тексте все понимать мне нужно менять пробовать тогда я лучше понимаю

Сергей Ракипов 08.09.2021 10:03

Я все правильно сделал или можно лучше или что то не учел?
Должно работать что если ширина такая то то значение высоты такое то.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        header{
            height: 500px;

        }
        footer{
            height: 1000px;
        }
        .blok{
            width: 80px;
            height: 80px;
            background-color:#D3D3D3;
            background-image: url(https://rakipov.ru/files/tsifra1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
        .blok.blok2{
            width: 80px;
            height: 80px;
            background-color:#000;
            background-image: url(https://rakipov.ru/files/icon1.svg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 70%;
            border-radius: 7px;
        }
    </style>
</head>
<body>
    <main>
        <header></header>
        <section>
            <article>
                <div class="blok"></div>
            </article>
        </section>
    </main>
    <footer></footer>

    <script>
        const blok = document.querySelector(".blok");
        const windowInnerWidth = document.documentElement.clientWidth;

        let anim1 = () => {
            if(windowInnerWidth >= 600){
            let ikonka1 = blok.getBoundingClientRect();
            blok.classList.toggle("blok2", ikonka1.top >= 100);
            }
            else if(windowInnerWidth >= 400){
            let ikonka1 = blok.getBoundingClientRect();
            blok.classList.toggle("blok2", ikonka1.top >= 200);
            }
            console.log(windowInnerWidth);
        };

        window.addEventListener("scroll", anim1);
        anim1(); 
    </script>
</body>
</html>

рони 08.09.2021 10:36

Сергей Ракипов,
изменяемый параметр лучше проверять перед условием! строку 51 перенесите в начало функции.


Часовой пояс GMT +3, время: 23:46.