http://jsbin.com/AyaDOVO/3/edit
我一直在尝试使用这个可绘制的div函数,我在隔离它时遇到了麻烦,因此只有在点击绘制按钮时才会调用它,并在单击开始按钮时禁用它。
这是我的JQuery / Javascript。
$(document).ready(function() {
var drawable = false;
$('.div-tool').click(function() {
drawable = true;
});
$('.select-tool').click(function() {
drawable = false;
});
function draw_a_box( e ) {
var pageX = e.pageX,
pageY = e.pageY,
dpLast = dp.find('.drawnBox.last'),
dpLast_data = dpLast.data();
$('.drawnBox').css({
'position': 'absolute',
'z-index': '1',
'border': '1px solid #222',
'background': '#e1e1e1',
'opacity': '0.5'
});
if ( e.type === 'mousemove' ) {
// If ".drawnBox.last" doesn't exist, create it.
if ( dpLast.length < 1 ) {
$('<div class="drawnBox last"></div>').appendTo( dp );
}
var drawCSS = {};
// If drawing is initiated.
if ( draw ) {
// Determine the direction.
// xLeft
if ( dpLast_data.pageX > pageX ) {
drawCSS.right = dp.width() - dpLast_data.pageX,
drawCSS.left = 'auto',
drawCSS.width = dpLast_data.pageX - pageX;
}
// xRight
else if ( dpLast_data.pageX < pageX ) {
drawCSS.left = dpLast_data.pageX,
drawCSS.right = 'auto',
drawCSS.width = pageX - dpLast_data.pageX;
}
// yUp
if ( dpLast_data.pageY > pageY ) {
drawCSS.bottom = dp.height() - dpLast_data.pageY,
drawCSS.top = 'auto',
drawCSS.height = dpLast_data.pageY - pageY;
}
// yDown
else if ( dpLast_data.pageY < pageY ) {
drawCSS.top = dpLast_data.pageY,
drawCSS.bottom = 'auto',
drawCSS.height = pageY - dpLast_data.pageY;
}
}
if ( !draw && dpLast.length > 0 ) {
dpLast.css({
top: pageY,
left: pageX
});
}
if ( draw ) {
dpLast.css( drawCSS );
}
}
if ( e.type === 'mousedown' ) {
e.preventDefault();
draw = true;
dpLast.data({ "pageX": pageX, "pageY": pageY });
}
else if ( e.type === 'mouseup' ) {
draw = false;
dpLast.removeClass('last');
}
}
if (drawable) {
var dp = $('#drawingArea'),
draw = false,
enabled = true;
dp
.css({ position: 'relative' })
.on("mousemove mousedown mouseup", draw_a_box );
}
});
答案 0 :(得分:1)
的 LIVE DEMO 强> 的
$(function(){ // DOM ready
var drawable = false,
drawing = false,
mS = {}, // mouse start
dBox;
$('#drawingArea').mousedown(function( e ){
if(drawable){
drawing = true;
mS.x = e.pageX;
mS.y = e.pageY;
dBox = $("<div class='drawnBox' />");
$(this).append(dBox);
}
});
$(document).mousemove(function(e){
if(drawing && drawable){
var mPos = {x:e.pageX, y:e.pageY};
var css = {};
css.left = (mPos.x > mS.x) ? mS.x : mPos.x;
css.top = (mPos.y > mS.y) ? mS.y : mPos.y;
css.width = Math.abs(mPos.x - mS.x);
css.height = Math.abs(mPos.y - mS.y);
dBox.css(css);
}
}).mouseup(function(e){
drawing = false;
});
$('.div-tool').click(function(){
drawable ^= 1; // TOGGLE
});
$('.select-tool').click(function() {
drawable = false; // OFF
});
}); // !DOM ready
注意,我已经将.drawnBox CSS从jQ放到了CSS。