做了很多东西都是用插件来完成,包括jquery.ui里面的resizeable和draggable都是用插件的~最近觉得,应该从基础开始慢慢学习,于是自己写基础插件。这次写resizable的方法,不一定对,只限参考:
resizable.js
(function(){
jQuery.fn.extend({
resizable: function(options){
var settings = {
maxWidth: null,
maxHeight: null,
minWidth: null,
minHeight: null,
container: ""
};
$.extend(settings, options);
var $this = $(this);
var $resizeIcon = $("<span></span>").addClass("resizable-icon").appendTo($this);
$resizeIcon.on("mousedown", function(){
$(document).on("mousemove", function(e){
e.preventDefault();
var coordX = $this.offset().top;
var coordY = $this.offset().left;
var pageX = e.pageX || e.offsetX;
var pageY = e.pageY || e.offsetY;
var height = pageY - coordY,
width = pageX - coordX;
var maxHeight = settings.maxHeight,
minHeight = settings.minHeight,
maxWidth = settings.maxWidth,
minWidth = settings.minWidth;
if(maxHeight){
maxHeight = settings.container?Math.min(maxHeight, $(settings.container).height()):maxHeight,
} else if(settings.container) {
maxHeight = $(settings.container).height();
}
if(maxWidth) {
maxWidth = settings.container?Math.min(maxWidth, $(settings.container).width()):maxWidth;
}else if(settings.container) {
maxWidth = $(settings.container).width();
}
height = maxHeight?Math.min(maxHeight, height) : height;
height = minHeight?Math.max(minHeight, height) : height;
width = maxWidth?Math.min(maxWidth, width) : width;
width = minWidth?Math.max(minWidth, width) : width;
$this.css({width: width, height: height});
});
$(document).on("mouseup", function(){
$(document).off("mousemove");
});
});
}
});
})(jQuery);
.resizable {
border: 1px dotted black; /*为现实效果,必须有边框*/
display: block !important; /*必须是block或者line-block*/
position: relative; /*用于resizable-icon的定位*/
overflow-y: auto;
word-wrap: break-word;
}
/*拖动块*/
.resizable-icon {
position: absolute;
right: 1px;
bottom: 1px;
cursor: se-resize;
background-color: red;
width: 8px;
height: 8px;
display: inline-block;
}
<!docttype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="resizable.css">
</head>
<body>
<div class="resizable">sdfsdffffff</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="resizable.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
js:
(function(){
$(".resizable").resizable({maxWidth: 500, minWidth: 200, minHeight: 200, maxHeight: 500, container: "body"});
})(jQuery);