我怎样才能制作一个可移动的<hr />?

时间:2016-05-30 21:50:29

标签: javascript css html5

我有一个问题。如何创建可移动的<hr>并将其移动到图像上? 我考虑过更改参数“margin”,但我不知道如何将<hr>放在图像上。

如果可以,请帮助我。

2 个答案:

答案 0 :(得分:0)

答案基于:https://jsfiddle.net/tovic/Xcb8d/

CSS

#draggable-hr {
    cursor:move;
    position: absolute;
    width: 100%;
}

HTML

<hr id="draggable-hr">

的JavaScript

var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

    // Will be called when user starts dragging an element
    function _drag_init(elem) {
        // Store the object of the element which needs to be moved
        selected = elem;
        x_elem = x_pos - selected.offsetLeft;
        y_elem = y_pos - selected.offsetTop;
    }

    // Will be called when user dragging an element
    function _move_elem(e) {
        x_pos = document.all ? window.event.clientX : e.pageX;
        y_pos = document.all ? window.event.clientY : e.pageY;
        if (selected !== null) {
            selected.style.left = (x_pos - x_elem) + 'px';
            selected.style.top = (y_pos - y_elem) + 'px';
        }
    }

    // Destroy the object when we are done
    function _destroy() {
        selected = null;
    }

    // Bind the functions...
    document.getElementById('draggable-hr').onmousedown = function () {
        _drag_init(this);
        return false;
    };

    document.onmousemove = _move_elem;
    document.onmouseup = _destroy;

答案 1 :(得分:0)

你为什么要这样做?

你想在图像中画一条线吗?为什么不使用帆布呢?这是一个例子:

https://jsfiddle.net/vo769cfx

  Original image:
<br>
<br>
<img id="scream" width="220" height="277" src="http://www.w3schools.com/tags/img_the_scream.jpg" alt="The Scream">
<br> Canvas:
<br>
<br>
<canvas id="myCanvas" width="320" height="277"></canvas>

  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var img = document.getElementById("scream");

  ctx.drawImage(img, 50, 0);
  ctx.beginPath();
  ctx.moveTo(0, 138);
  ctx.lineTo(320, 138);
  ctx.stroke();

每次在画布上单击或拖动时,只需重新绘制线条。