首页 > 解决方案 > How do I change the left margin of div based on scroll and using javascript?

问题描述

I am new to Javascript and CSS. I have a div that will contain an image. The below code, I pieced it together after watching some YouTube videos and going over some documentation, however I am sure that this is not the right code.

https://jsfiddle.net/0hp97a6k/

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: powderblue;
  height: 2000px;
  padding: 0 0;
}

div {
  margin: 0;
}

.headerspace {
  width: 100%;
  height: 20px;
  background-color: white;
}

.header {
  width: 100%;
  height: 300px;
  background-color: maroon;
  display: flex;
}

.logo {
  width: 200px;
  height: 200px;
  background-color: red;
  margin-top: 50px;
  margin-left: 50px;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="headerspace"></div>
  <div class="header">
    <div class="logo" id="logoid">
    </div>
  </div>



  <script type="text/javascript">
    let logo = document.getElementById("logoid");

    window.addEventListener('scroll', function() {
      var value = window.scrollY;

      logo.style.marginleft = value * 0.5 + 'px';
    })
  </script>

</body>

</html>

How do I set the left margin based on scroll?

Also can scroll based properties be applied to two margins, say top and right at the same time?

标签: javascripthtmlcssscroll

解决方案


marginleft should be marginLeft in your javascript

<script type="text/javascript">
    let logo = document.getElementById("logoid");

    window.addEventListener('scroll', function(){
        var value = window.scrollY;

        logo.style.marginLeft = value * 0.5 + 'px';
    })

</script>

And then if you want to edit the left and top you can do the following

<script type="text/javascript">
    let logo = document.getElementById("logoid");

    window.addEventListener('scroll', function(){
        var value = window.scrollY;

        logo.style.marginLeft = value * 0.5 + 'px';
        logo.style.marginTop = value * 0.5 + 'px';
    })

</script>

To make sure the logo element goes back where it started you should edit the css like this

* {
margin: 0;
padding: 0;
}
body {
    background-color: powderblue;
    height: 2000px;
    padding: 0 0;
}
div{
    margin: 0;
}
.headerspace{
    width: 100%;
    height: 20px;
    background-color: white;
}
.header{
    width: 100%;
    height: 300px;
    background-color: maroon;
    display: flex;
    padding-top: 50px;
    padding-left: 50px;
}
.logo{
    width: 200px;
    height: 200px;
    background-color: red;
}

I have removed the margin from .logo because that will be overwritten and added those values as padding to the parent (.header)


推荐阅读