I am utilizing the Jquery UI resizable plugin in order to resize various div's. Consider the following HTML page (with JS embedded):
<html>
<head></head>
<body>
<div id="site">
<div>This element is resizable</div>
<br />
<div style="width: 200px;">This is another resizable element</div>
</div>
<!-- javascript includes -->
<script>
$(function() {
$("#site d开发者_如何学Pythoniv").click(function() {
console.log("Clicked");
if($(this).hasClass("selected")) {
$(this).removeClass("selected");
}
else { // Currently not selected, so let's select it
$(this).addClass("selected").resizable({
start: function(event, ui) {
console.log("Start");
},
resize: function(event, ui) {
console.log("Resize");
},
stop: function(event, ui) {
console.log("Stop");
}
});
}
});
});
</script>
</body>
</html>
So, what I'm trying to accomplish in this sample code is pretty simple. When a user clicks on a div nested within "#site", I want the div to become "selected". So, in this example, when the click event for the div is fired, a CSS class called "selected" will be added to the clicked div. In addition to clicking the div, the user can resize the div. The problem arises when the user resizes the selected div. Obviously, a click event fires when the user first selects a div, but a click event also fires when the user clicks and drags the edges of the div to resize it. The click event will call the click routine and de-select the div. This is not what I want to happen. The click event fires only after all the resizable events have fired.
With that, my question is, how could I handle this scenario to allow the user to click and select the div, but also to allow the div to be resized, but not de-selected when the div is dragged and resized? Your help is appreciated. Thanks in advance.
Good question. Resizable is utilizing event bubbling. The actual resize handles are inner elements of your resizable. So, checking the class of the event target will give you what you need.
http://jsfiddle.net/bmvDs/1/
$('#test').click(function(e){
if(!$(e.target).is('.ui-resizable-handle')) // not if it is the handle
$(this).toggleClass('selected');
}).resizable();
One option might be to set all your divs as resizable from the outset and handle the styles on click:
$(function() {
var resizables = $('#site div');
resizables.resizable({
start: function(event, ui) {
console.log("Start");
// Remove the selected class from all other divs first
resizables.each(function(){ $(this).removeClass('selected'); });
// Set this div as selected
ui.element.addClass('selected');
// Carry on doing whatever else you want to do
},
resize: function(event, ui) {
console.log("Resize");
},
stop: function(event, ui) {
console.log("Stop");
}
});
});
jQuery .one is your friend! This will allow a single click on each element with class .foo.
$(".foo").one("click", function() {
alert("This will be displayed only once.");
});
精彩评论