在拖动w / jQuery时向元素添加CSS类 [英] Add CSS class to an element while dragging over w/ jQuery

查看:90
本文介绍了在拖动w / jQuery时向元素添加CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在元素被拖曳到特定区域时向元素添加CSS类,并在元素被删除后替换该类?



解决方案

是的,这当然是可能的。 jQuery UI提供了一些方便的选项和事件来做到这一点。



对于初学者,draggable元素总是可以由类 .ui-



droppable 方法然后提供一个事件调用 over ,当有效的可拖动对象悬停在其上时,它将执行一个函数。所以,在这个函数中,我们可以参考 .ui-draggable-dragging 并添加一个类。



还提供了 Out drop 事件,我们可以以同样的方式定位draggable元素。下面是它的外观:

  $(#droppable)。droppable({
// tolerance设置为'fit','intersect','pointer'或'touch'
tolerance:'intersect',
//添加.hoverClass #draggable被悬停在#droppable
:remove();
};
//删除.hoverClass每当#draggable不再徘徊在#droppable
out:function(event,ui){
$('。ui-draggable-dragging')。removeClass('hoverClass');
},
//当#draggable放在#droppable上时添加.dropClass
drop:function(event,ui){
$('。ui-draggable-dragging')。removeClass('hoverClass' ).addClass('dropClass');
}
});

上述代码在 #draggable #droppable 相交,然后将 #draggable 替换为# droppable 。另外,当两个元素不再相交时, .hoverClass 被删除。这是 jsfiddle的工作示例



希望有帮助。 p>

Is it possible to add a CSS class to an element while it is being dragged over a particular area and replace the class once the element is dropped?

I am not looking for this feature everywhere, but only over a particular area.

解决方案

Yep, it's certainly possible. jQuery UI provides some handy options and events to do this.

For starters, the draggable element can always be referred to by the class .ui-draggable-dragging while it's being dragged.

The droppable method then provides an event called over which will execute a function whenever a valid draggable object is hovered over it. So, inside that function we can refer to .ui-draggable-dragging and add a class to it.

Out and drop events are also offered and we can target the draggable element the same way. Here's how it would look:

$("#droppable").droppable({
    // tolerance can be set to 'fit', 'intersect', 'pointer', or 'touch'
    tolerance: 'intersect',
    // Add .hoverClass whenever #draggable is being hovered over #droppable
    over: function(event, ui) {
        $('.ui-draggable-dragging').addClass('hoverClass');
    },
    // Remove .hoverClass whenever #draggable is no longer hovered over #droppable
    out: function(event, ui) {
        $('.ui-draggable-dragging').removeClass('hoverClass');
    },
    // Add .dropClass whenever #draggable is dropped on #droppable
    drop: function(event, ui) {
        $('.ui-draggable-dragging').removeClass('hoverClass').addClass('dropClass');
    }
});

The above code adds a class when #draggable intersects with #droppable and then replaces that class when #draggable is dropped on to #droppable. Additionally, .hoverClass is removed when the two elements no longer intersect. Here is a working example on jsfiddle.

Hope that helps.

这篇关于在拖动w / jQuery时向元素添加CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆