整个页面
require.js官网
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> *{
margin: 0px; padding: 0px;} #div1{
width: 200px; height: 200px; background-color: red; position: relative; display: none;} #div2{
width: 50px; height: 50px; background-color: yellow; position: absolute; right: 0; bottom: 0;} #div3{
width: 100px; height: 100px; background-color: blue; position: absolute; right: 0; top: 0;} </style>
<script src="js/require.js" async = 'true' defer data-main="js/main"></script>
</head>
<body>
<button id="btn1">点击按钮</button>
<div id="div1">
<div id="div2"></div>
</div>
<div id="div3"></div>
</body>
</html>
main.js
console.log("jiazaichengong");
require.config({
//给index.js和scle.js和drag.js配置路径
paths: {
index: "index",
scale: "scle",
drag: "drag"
}
})
require(["index"], function(index) {
index.init();
});
index.js(调用别的模块的js方法来操作dom)
define(["scale","drag"],function(scale,drag){
function init() {
const btn = document.getElementById("btn1");
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");
btn.onclick = function() {
div1.style.display = "block";
}
scale.scale(div1,div2);
drag.drag(div3);
}
return {
init: init
}
})
拖拽方法drag.js
define(function(){
function drag(node) {
node.onmousedown = function(ev) {
let e = ev || window.event;
let offsetX = e.clientX - this.offsetLeft;
let offsetY = e.clientY - this.offsetTop;
document.onmousemove = function(ev) {
let e = ev || window.event;
let l = e.clientX - offsetX;
let t = e.clientY - offsetY;
let windowWidth = document.documentElement.clientWidth;
let windowHeight = document.documentElement.clientHeight;
l = range(l,0,windowWidth - node.offsetWidth);
t = range(t,0,windowWidth - node.offsetHeight);
node.style.left = l + 'px';
node.style.top = t + 'px';
}
}
document.onmouseup = function() {
document.onmousemove = null;
}
}
function range(i,min,max) {
if(i > max) {
return max;
}else if(i < min) {
return min;
}else{
return i;
}
}
return {
drag: drag,
range: range
}
})
缩放模块scle.js
define(["drag"],function(drag){
function scale(node1,node2) {
node2.onmousedown = function(ev) {
let e = ev || window.event;
let w = node1.offsetWidth;
let h = node1.offsetHeight;
let l = e.clientX;
let t = e.clientY;
document.onmousemove = function(ev) {
let e = ev || window.event;
let W = w + (e.clientX - l);
let H = h+ (e.clientY - t);
W = drag.range(W,100,500);
H = drag.range(H,100,500);
node1.style.width = W + 'px';
node1.style.height = H + 'px';
}
}
document.onmouseup = function() {
document.onmousemove = null;
}
}
return {
scale: scale
}
})