2017-01-19 19 views
2

水平線の中央に自動的にスクロールして、赤い線(svgの真ん中に置かれています)が中央にくるようにします。div内の水平方向に自動的に水平にスクロールするには?

scrollLeftにはどの値を選択する必要がありますか?

var div = $('.container'); 
 
div.animate({ 
 
    scrollLeft: div.width()/2 + div.offset().left 
 
});
.container { 
 
    height: 200px; 
 
    width: 400px; 
 
    border: 1px solid black; 
 
    overflow: scroll; 
 
    margin-left: 50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class=container> 
 
    <svg width="1000" height="400"> 
 
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="200" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="600" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="40" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="960" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 

 
    <line x1="499" y1="0" x2="499" y2="400" style="stroke:rgb(255,0,0);stroke-width:2" /> 
 

 
    </svg> 
 
</div>

答えて

1

あなたは以下のようにscrollLeftプロパティを設定する必要があります参照してくださいデモ以下

div.find('svg').width()/2 - div.width()/2 

var div = $('.container'); 
 
div.animate({ 
 
    scrollLeft: div.find('svg').width()/2 - div.width()/2 
 
});
.container { 
 
    height: 200px; 
 
    width: 400px; 
 
    border: 1px solid black; 
 
    overflow: scroll; 
 
    margin-left: 50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class=container> 
 
    <svg width="1000" height="400"> 
 
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="200" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="600" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="40" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 
    <circle cx="960" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> 
 

 
    <line x1="499" y1="0" x2="499" y2="400" style="stroke:rgb(255,0,0);stroke-width:2" /> 
 

 
    </svg> 
 
</div>

関連する問題