2016-07-21 6 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; 
} 

あなたがそこに見ることができるようにそれがようであれば、あなたのコードは動作しますがその..


しかし、今、私はあなたの現在のシナリオにベースます。..

NOW WORKING jQuery("body")

でなければなりませんjQuery("#parent")から

は、次のとおりです。

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

jQuery("html,body").animationないために行く私は、ボタンのクリックで任意のアニメーションが表示されません。 – vijayP

0

コードの下を見てください。スクロールアニメーションの#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>

関連する問題