2016-07-21 67 views
0

我有以下代碼。我試圖通過點擊一個按鈕水平滾動到一個div。滾動到橫向不工作的div

jQuery(document).ready(function() { 
 
    jQuery("#clickme").click(function() { 
 

 
    jQuery("#parent").animate({ 
 
     scrollLeft: jQuery("#child").position().left 
 
    }, 500); 
 
    }); 
 
});
#parent { 
 
    width: 1000px; 
 
    height: 200px; 
 
    background: #ccc; 
 
    position: relative; 
 
} 
 
#child { 
 
    position: absolute; 
 
    right: 200px; 
 
    height: 100px; 
 
    width: 100px; 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="parent"> 
 
    <button id="clickme"> 
 
    Click Me 
 
    </button> 
 
    <div id="child"> 
 
    child div 
 
    </div> 
 
</div>

有控制檯沒有錯誤。我究竟做錯了什麼 ?

回答

3

「這是你應該有動畫的身體,因爲它是一個有滾動條的人。」

你的代碼應該是正確的,如果情況像this

(只要改變你的CSS像這樣)

#parent { 
    width: 350px; /* Make it shorter for scroll to work */ 
    height: 200px; 
    background: #ccc; 
    position: relative; 
    overflow: scroll; /* To show scrollbar */ 
} 
#child { 
    position: absolute; 
    right: -150px; /* Make it negative also to make scroll working */ 
    height: 100px; 
    width: 100px; 
    background: blue; 
} 

正如你可以看到有,如果是喜歡你的代碼會工作這..


但現在,我會根據你目前的情況..

jQuery("#parent"),是應該jQuery("body")

現在的工作:

jQuery(document).ready(function() { 
 
    jQuery("#clickme").click(function() { 
 

 
    jQuery('body').animate({ 
 
     scrollLeft: jQuery("#child").position().left 
 
    }, 500); 
 
    }); 
 
});
#parent { 
 
    width: 1000px; 
 
    height: 200px; 
 
    background: #ccc; 
 
    position: relative; 
 
} 
 
#child { 
 
    position: absolute; 
 
    right: 200px; 
 
    height: 100px; 
 
    width: 100px; 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="parent"> 
 
    <button id="clickme"> 
 
    Click Me 
 
    </button> 
 
    <div id="child"> 
 
    child div 
 
    </div> 
 
</div>

+0

我看不到按鈕,點擊任何動畫。 – vijayP

0

請看看下面的代碼。對於滾動動畫去jQuery("html,body").animation而不是與#parent

jQuery(document).ready(function() { 
 
    jQuery("#clickme").click(function() { 
 

 
    jQuery("html,body").animate({ 
 
     scrollLeft: jQuery("#child").position().left 
 
    }, 500); 
 
    }); 
 
});
#parent { 
 
    width: 1000px; 
 
    height: 200px; 
 
    background: #ccc; 
 
    position: relative; 
 
} 
 
#child { 
 
    position: absolute; 
 
    right: 200px; 
 
    height: 100px; 
 
    width: 100px; 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="parent"> 
 
    <button id="clickme"> 
 
    Click Me 
 
    </button> 
 
    <div id="child"> 
 
    child div 
 
    </div> 
 
</div>