Home Web Front-end HTML Tutorial HTML realizes dragging content position at will

HTML realizes dragging content position at will

Jul 20, 2020 pm 01:06 PM

HTML realizes dragging content position at will

Two ways are: dragging the normal label position or dragging the text box position in the canvas

1. Implement mouse dragging of labels Element to any position

css code

#range {
    position: relative;
    width: 600px;
    height: 400px;
    margin: 10px;
    background-color: rgb(133, 246, 250);
}

.icon {
    position: absolute;
    height: 100px;
    width: 100px;
    cursor: move;
    background-color: #ff9204;
    user-select: none;
}
Copy after login

html code

<p id="range">
    <p class="icon">100*100</p>
</p>
Copy after login

js code

const main = document.getElementById(&#39;range&#39;);
const icon = document.querySelector(&#39;.icon&#39;);
let move = false;
let deltaLeft = 0, deltaTop = 0;

// 拖动开始事件,要绑定在被移动元素上
icon.addEventListener(&#39;mousedown&#39;, function (e) {
    /*
    * @des deltaLeft 即移动过程中不变的值
    */
    deltaLeft = e.clientX-e.target.offsetLeft;
    deltaTop = e.clientY-e.target.offsetTop;
    move = true;
})

// 移动触发事件要放在,区域控制元素上
main.addEventListener(&#39;mousemove&#39;, function (e) {
    if (move) {
        const cx = e.clientX;
        const cy = e.clientY;
        /** 相减即可得到相对于父元素移动的位置 */   
        let dx = cx - deltaLeft
        let dy = cy - deltaTop

        /** 防止超出父元素范围 */
        if (dx < 0) dx = 0
        if (dy < 0) dy = 0
        if (dx > 500) dx = 500
        if (dy > 300) dy = 300
        icon.setAttribute(&#39;style&#39;, `left:${dx}px;top:${dy}px`)
    }
})

// 拖动结束触发要放在,区域控制元素上
main.addEventListener(&#39;mouseup&#39;, function (e) {
    move = false;
    console.log(&#39;mouseup&#39;);
})
Copy after login

2 .Canvas draws a text box and drags it to any position with the mouse

css code

.cus-canvas{
    background: rgb(50, 204, 243);
}

.input-ele{
    display: none;
    position: fixed;
    width: 180px;
    border: 0;
    background-color: #fff;
}
Copy after login

html code

<p>
    <canvas id="canvas" class="cus-canvas"  width="800" height="600"></canvas>
    <input id="inputEle" class="input-ele"/>
</p>
Copy after login

js code

The implementation principle is to record the position of the mouse movement and continuously redraw the rectangular frame and text content

let mouseDown = false;
let deltaX = 0;
let deltaY = 0;
let text = &#39;hello&#39;
const canvas = document.getElementById(&#39;canvas&#39;);
const ctx = canvas.getContext(&#39;2d&#39;);
const cw = canvas.width, ch = canvas.height;
const rect = {
    x: 20,
    y: 20,
    width: 150,
    height: 50
}

/** 设置文字和边框样式 */
ctx.font="16px Arial";
ctx.fillStyle = "#fff"; 
/** 设置为 center 时,文字段的中心会在 fillText的 x 点 */
ctx.textAlign = &#39;center&#39;;
ctx.lineWidth = &#39;2&#39;;
ctx.strokeStyle = &#39;#fff&#39;;

strokeRect()

const inputEle = document.getElementById(&#39;inputEle&#39;);
inputEle.onkeyup =  function(e) {
    if(e.keyCode === 13) {
        text = inputEle.value
        strokeRect()
        inputEle.setAttribute(&#39;style&#39;, `display:none`)
    }
}

canvas.ondblclick = function(e){ 
    inputEle.setAttribute(&#39;style&#39;, `left:${e.clientX}px;top:${e.clientY}px;display:block`);
    inputEle.focus();
}

canvas.onmousedown = function(e){ 
    /** 获取视口左边界与canvas左边界的距离 加上 鼠标点击位置与canvas左边界的长度,这个值是相对移动过程中不变的值 */
    deltaX=e.clientX - rect.x;
    deltaY=e.clientY - rect.y;
    mouseDown = true
};  

const judgeW = cw-rect.width, judgeH = ch-rect.height;

canvas.onmousemove = function(e){ 
    if(mouseDown) {
        /** 相减即可获得矩形左边界与canvas左边界之间的长度 */
        let dx = e.clientX-deltaX; 
        let dy = e.clientY-deltaY; 
        if(dx < 0) {
            dx = 0;
        } else if (dx > judgeW) {
            dx = judgeW;
        }
        if(dy < 0) {
            dy = 0;
        } else if(dy > judgeH) {
            dy = judgeH;
        }
        rect.x = dx;
        rect.y = dy; 
        strokeRect()
    }
};  
canvas.onmouseup = function(e){ 
    mouseDown = false
};  

/** 清除指定区域 */
function clearRect() {
    ctx.clearRect(0, 0, cw, ch)
}

/** 画矩形 */
function strokeRect() {
    clearRect()

    /** 这里如果不调用 beginPath 历史的矩形会重新被绘制 */
    ctx.beginPath() 
    ctx.rect(rect.x, rect.y, rect.width, rect.height)
    ctx.stroke();
    // 设置字体内容,以及在画布上的位置
    ctx.fillText(text, rect.x + 70, rect.y + 30);
}
Copy after login

Recommended tutorial: "HTML Tutorial"

The above is the detailed content of HTML realizes dragging content position at will. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

See all articles