Написал скрипт, помогите упростить.
Drag&Drop скрипт. Подскажите в каких местах можно упростить.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
jQuery.fn.extend({
disableSelection : function() {
this.each(function() {
jQuery(this).css('-moz-user-select', 'none');
this.onselectstart = function() {
return false;
};
this.unselectable = "on";
});
},
enableSelection : function() {
this.each(function() {
jQuery(this).css('-moz-user-select', 'auto');
this.onselectstart = function() {};
this.unselectable = "off";
});
}
});
$('#charge, #volume').live('mousedown', function(event){
element = $(this).find('div:last');
$(element).disableSelection();
father = element.parent();
cursor = event.pageX - element.width()/2;
drag(event);
function drag(event) {
cursor = event.pageX - element.width()/2;
left = father.offset().left;
right = left + father.width() - element.width();
if(left < cursor) {
if(cursor < right) {
margin = cursor - left;
} else {
margin = right - left;
}
} else {
margin = 0;
}
element.css('margin-left', margin+'px');
};
$(document).bind('mousemove', drag);
$(document).one('mouseup', function(){
$(element).enableSelection();
$(this).unbind('mousemove');
});
});
</script>
<style>
#charge, #volume {
margin-bottom: 5px;
background: #eee;
width: 200px;
height: 5px;
}
#charge div {
background: #ccc;
width: 100px;
height: 5px;
}
#charge div div, #volume div {
background: #000;
height: 5px;
width: 10px;
}
</style>
<div id="charge"><div><div></div></div></div>
<div id="volume"><div></div></div>
|
Цитата:
this.onselectstart = null; |
Спасибо, первый пост обновил.
|
Можно улучшить и упростить (комментарии для тех кто плохо знает английский):
$('#charge, #volume').live('mousedown', function(event){
var $element = $(this).find('div:last'),
element = new Draggable($element);
$element.disableSelection();
element.drag(cursorPosition(event));
$(document).bind('mousemove', function(event){
element.drag(cursorPosition(event));
});
$(document).one('mouseup', function(){
$element.enableSelection();
$(this).unbind('mousemove');
});
// function позицияКурсора(событие) {...
function cursorPosition(event) {
return event.pageX - $element.width()/2;
}
});
// function Перетаскиваемый($элемент) {...
function Draggable($element) {
// function перетащить(позиция) {...
this.drag = function(position) {
var margin = 0;
if (parentLeftEdge() < position) {
if (position < parentRightEdge()) {
margin = position - parentLeftEdge();
} else {
margin = parentRightEdge() - parentLeftEdge();
}
}
$element.css('margin-left', margin+'px');
};
// function леваяГраницаРодителя() {...
function parentLeftEdge() {
return $element.parent().offset().left;
}
// function праваяГраницаРодителя() {...
function parentRightEdge() {
return parentLeftEdge() + $element.parent().width() - $element.width();
}
}
|
| Часовой пояс GMT +3, время: 17:37. |