6
4

More than 5 years have passed since last update.

jQuery UI:Draggableエレメントをクリックで最前面へ

Posted at

Draggableのstackオプションを使うことで、ドラッグ時にエレメントを最前面を持ってくることができます。例えばこんな感じ

    $('.draggable-box').draggable({ stack: ".draggable-box" });

これでもまぁいいんだけど、やっぱりクリックしたときに最前面に来てほしい。

ということで書いてみた。

click-on-top.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Draggable test</title>
    <style type="text/css">
    .draggable-box {
        height: 100px;
        width: 100px;
        border-style: solid;
    }
    #id1 {
        background-color: #8080ff;
        border-color: #0000ff;
        z-index: 1;
    }
    #id2 {
        background-color: #ff8080;
        border-color: #ff0000;
        z-index: 2;
    }
    #id3 {
        background-color: #80ff80;
        border-color: #00ff00;
        z-index: 3;
    }
    </style>
</head>
<body>
    <div>
        <div id="id1" class="draggable-box"></div>
        <div id="id2" class="draggable-box"></div>
        <div id="id3" class="draggable-box"></div>
    </div>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
    <script>
    $('.draggable-box').draggable();

    $('.draggable-box').mousedown(function () {
        var boxes = [],
            self = this,
            myIndex;

        $('.draggable-box').each(function (i) {
            boxes[i] = {
                box: this,
                zIndex: Number($(this).css('z-index'))
            };
            if (this === self) {
                myIndex = i;
            }
        });
        boxes[myIndex].zIndex = boxes.length + 1;
        boxes.sort(function (a, b) {
            if (a.zIndex < b.zIndex) return -1;
            if (a.zIndex > b.zIndex) return 1;
            return 0;
        });

        boxes.forEach(function (item, i) {
            $(item.box).css('z-index', i + 1);
        });
    });
    </script>
</body>
</html>

mousedownイベントで、クリックされたエレメントのz-indexの値を一番大きい値に変更しています。z-indexの値がどんどん大きくなるのは好きじゃないので、ソートして値を振り直しています。

stackオプションでも結局はz-indexの値を再設定しているようですが、素直に一番大きい値に変更するだけのようで、z-indexの値がどんどん大きくなるっぽい。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4