How can I change the background color of multiple divs by dragging over them with the (clicked) mouse?

StackOverflow https://stackoverflow.com/questions/22550424

문제

Please have a look at this example.

I have 4 divs here with white background. When I click on a div, its background changes into blue. When I click it again background switches back to white.

Now I want to highlight multiple divs by dragging over them: I click on the first div and hold the mouse button down. The div gets blue. With the clicked button I can drag over the other divs now and their color is changed as soon as the cursor is over the element.

I haved tried some things with JQuery's .mousedown Function but I did not get it to work.

HTML:

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

CSS

.box{
    float: left;
    height: 100px;
    width: 100px;
    border: 1px solid #000;
    margin-right: 10px;
}

.highlight{
    background: #0000FF;
}

JS

$(document).ready(function(){
   $('.box').click(function(){
        if($(this).hasClass('highlight')){
            $(this).removeClass('highlight');
        }
        else{
            $(this).addClass('highlight');
        }
    });
});
도움이 되었습니까?

해결책

You can use the mouseenter event to handle it

$(document).ready(function () {
    var $box = $('.box').mousedown(function () {
        $(this).toggleClass('highlight');
        var flag = $(this).hasClass('highlight')
        $box.on('mouseenter.highlight', function () {
            $(this).toggleClass('highlight', flag);
        });
    });
    $(document).mouseup(function () {
        $box.off('mouseenter.highlight')
    })
});

Demo: Fiddle

다른 팁

Try,

$(document).ready(function () {
    var isMouseClicked = false
    $('.box').mousedown(function () {
        isMouseClicked = true;
    }).mouseup(function () {
        isMouseClicked = false;
    }).mousemove(function () {
        if (isMouseClicked) {
            $(this).addClass("highlight");
        }
    });
});

DEMO or http://jsfiddle.net/Vk24X/2/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top