简体   繁体   中英

scrollTop works in Mozilla but not in Chrome

I want to add a scrollTop animation via JavaScript. It works fine in Mozilla but not at all in Chrome. Clicking on the link in Chrome does nothing.

Here is my code:

<script type="text/javascript">

        $(document).ready(function() {
            $('a[href=#smart_tshirt]').click(function(){

                $('html, body').animate({scrollTop:1400}, 'slow');                    
            });
            $('a[href=#smart_tshirt2]').click(function(){

                $('html, body').animate({scrollTop:1400}, 'slow');                    
            });       
          return false;
        });              
    </script>

<div style="top: 0px; left: 140px; font-size: 32px; text-align: left; width: 100%;      
height: 47px; font-family: 'League Gothic'; color: rgb(102, 102, 102); line-height: 
25px;   float: left;"><a href="#smart_tshirt" id="#smart_tshirt">Smart<br />

T-shirt</a></div>

<div style="top: 80px; left: 140px; font-size: 14px; text-align: left; height: 100px;    
font-family: 'Carrois Gothic',sans-serif; color: rgb(102, 102, 102); line-height: 19px;  
width: 130px; float: left;">With integrated cardiac sensors.</div>


<div style="top: 29px; left: 260px; width: 19px; height: 19px; float: left;"><a   
href="#smart_tshirt2" id="#smart_tshirt2"><img alt="smart t-shirt" 
src="images/universo/flechaNar.jpg" /></a></div>

</div>

What do you want to accomplish with return false; in your global Object? This must be added in your click event to prevent the normal behaviour.

<script type="text/javascript">
    $(document).ready(function() {
        $('a[href*="#smart_tshirt"]').on('click', function() {
            $('html, body').animate({ scrollTop: 1400 }, 'slow');  

            return false;
        });
    });              
</script>

Also you don't have to double your function just because the second href="" of <a> contains a number. Just use a[href*="#"] which means attribute contains selector . Read more about that here .

The second problem is, that you can't start an ID with # or numbers. ID's and classes must always start with letters. Edit your HTML like this and everything works well.

<a href="#smart_tshirt" id="smart_tshirt">Smart T-shirt</a>

Working example: http://jsfiddle.net/3mPfc/10/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM