0

マウスのクリックで円を 50% 縮小しようとしています。jQuery UI のスケール効果を使用してそれを行いました。

ディビジョンは

<div id='circle' class='circle'></div>

Jsは

var percent = 0.5;

$('#circle').click(function () {
    var height = $(this).height();
    var width = $(this).width();
    var centerX = $(this).position().left + $(this).width()/2.0;
    var centerY = $(this).position().top + $(this).height()/2.0;
    $(this).effect( "scale", { percent: percent * 100 }, 1000, function () {
        var newTop = centerY - (height * percent)/2.0;
        var newLeft = centerX - (width * percent)/2.0;
        $('#circle').offset({ 'top': newTop, 'left': newLeft });
        $('#circle').css({'height': height * percent, 'width': width * percent });
    });
});

そのコードは、円に次のようなテキストを追加するまで機能しました

<div id='circle' class='circle'>
  <span class="title">Title</span>
</div>

タイトルは円とともに縮小されましたが、完成すると元のサイズに戻り、円は楕円形になりました。このフィドルを試してください: http://jsfiddle.net/marsant/Ycakg/

完了コールバックを手動で微調整する以外に、この問題を解決する適切な方法はありますか? ありがとう!

4

1 に答える 1

2

次のようなものを追加することで、簡単に修正できます。

$(this).find('*').filter(function(i) { return $(this).text != "" && !$(this).children().length }).each(function(i) {
    var curSize = parseFloat($(this).css('fontSize'));
    $(this).css('fontSize', curSize / 2);
});
  • $(this).find('*'): 円 div のすべての内部要素を取得します
  • .filter(function(i) { return $(this).text != "" && !$(this).children().length }): テキストを持ち、他の内部要素を持たない内部要素のみに結果を絞り込みます
  • .each(function(i) {: フォント サイズを変更できるように、各要素の処理を開始します。
  • var curSize = parseFloat($(this).css('fontSize'));: 現在の内部要素の現在のフォント サイズを取得します
  • $(this).css('fontSize', curSize / 2);: この内側の要素のフォントを、古いフォントの半分の新しいフォント サイズに設定します。

蘇生に合わせて少し派手にしたい場合は、次のようにします。

var curSize = parseFloat($(this).css('fontSize')),
        newSize = curSize / 2
    $(this).animate({ fontSize: newSize });

アニメーションと正確に一致させたい場合は、おそらく CSS ソリューションを見つけるか、スクリプト全体を少し変更する必要があります。ちょっと見てみます...

WORKING EXAMPLE


Animate を使用してすべてを一度に実行する:

$('#circle').click(function () {
    var height = $(this).height(),
        newHeight = height / 2,
        width = $(this).width(),
        newWidth = width / 2,
        fontSize = parseFloat($(this).css('fontSize')),
        newFontSize = fontSize / 2,
        newLeft = parseFloat($(this).css('left')) + (newWidth / 2),
        newTop = parseFloat($(this).css('top')) + (newHeight / 2);

    $(this).animate({ 
        height: newHeight,
        fontSize: newFontSize,
        left: newLeft,
        top: newTop,
        width: newWidth 
    });
});

これには、CSS のわずかな変更が必要です。を変更.circleして位置relativeを変更し、をに移動font-size: 80px;します.circle

.circle {
    background:red;
    border-radius: 50%;
    height: 200px;
    width: 200px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    top: 10px;
    left: 10px;
    font-size: 80px;    
    position: relative;
}
.title {
    color: #fff;
    font-family:'Helvetica';
}

WORKING EXAMPLE

于 2013-09-30T19:07:43.923 に答える