Working with CSS, top propery in JQuery

前端 未结 3 1180
余生分开走
余生分开走 2021-01-29 10:52

I want to change top position of class bbb after 100 ms, but it took out that .css(top) does not work.

Please help.



&l         


        
相关标签:
3条回答
  • 2021-01-29 11:33

    As others have already said, if you want to use the top attribute you need to give

    position:relative;
    

    to the element. This way the element will be set relative to his position and this could be a little tricky. By the way i usually prefer to make a container box relative ad put the positionable element absolute in it, so it will be displayed relative to his container:

    .container{
        position:relative;
    }
    
    .element{
        position:absolute;
    }
    

    This is the html:

    <div class="container">
         <div class="element"></div>
    </div>
    
    0 讨论(0)
  • 2021-01-29 11:42

    You should use setTimeout() instead of setInterval() this way alertFun() will only run once.

    let alertFunc = function() {
    
      $('.bbb').css('top', 100 + 'px');
    
    }
    
    setTimeout(alertFunc, 100);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="ffffd">
      <div class='bbb'>Bobobo</div>
    </div>

    0 讨论(0)
  • 2021-01-29 11:43

    Just like @jhpratt mentioned. You need to add position:relative to the .bbb class.

    See below.

    $(function myFunction() {
      setTimeout(alertFunc, 500);
    });
    
    function alertFunc() {
      var b = $('.bbb').first();
      b.css('top', 100 + 'px');
    }
    .bbb {
      position: relative;
      border: 1px solid red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <div class="ffffd">
      <div class='bbb'>Bobobo</div>
    </div>

    0 讨论(0)
提交回复
热议问题