代码在JSfiddle中有效,但在本地主机上无效

时间:2017-02-02 21:51:04

标签: javascript html css jsfiddle

我正在尝试创建一个实时渲染框,我可以单击并拖动进行缩放。我找到了这个例子,

http://jsfiddle.net/d9BPz/546/

但是当我在本地运行它时,什么都没有出现。我认为它与CSS样式有关。我以为你不允许给JS变量CSS样式。

.rectangle {
border: 1px solid #FF0000;
position: absolute;
}

我确保在索引文件中正确添加javascript和css文件。

1 个答案:

答案 0 :(得分:1)

在本地计算机中,在<div id="canvas"></div>

之后在脚本中编写脚本
<html>
<head>
<style>
#canvas {
    width:2000px;
    height:2000px;
    border: 10px solid transparent;
}
.rectangle {
    border: 1px solid #FF0000;
    position: absolute;
}
</style>
</head>
<body>
<div id="canvas"></div>
<script>
initDraw(document.getElementById('canvas'));



function initDraw(canvas) {
    function setMousePosition(e) {
        var ev = e || window.event; //Moz || IE
        if (ev.pageX) { //Moz
            mouse.x = ev.pageX + window.pageXOffset;
            mouse.y = ev.pageY + window.pageYOffset;
        } else if (ev.clientX) { //IE
            mouse.x = ev.clientX + document.body.scrollLeft;
            mouse.y = ev.clientY + document.body.scrollTop;
        }
    };

    var mouse = {
        x: 0,
        y: 0,
        startX: 0,
        startY: 0
    };
    var element = null;
    canvas.onmousemove = function (e) {
        setMousePosition(e);
        if (element !== null) {
            element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
            element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
            element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
            element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
        }
    }

    canvas.onclick = function (e) {
        if (element !== null) {
            element = null;
            canvas.style.cursor = "default";
            console.log("finsihed.");
        } else {
            console.log("begun.");
            mouse.startX = mouse.x;
            mouse.startY = mouse.y;
            element = document.createElement('div');
            element.className = 'rectangle'
            element.style.left = mouse.x + 'px';
            element.style.top = mouse.y + 'px';
            canvas.appendChild(element)
            canvas.style.cursor = "crosshair";
        }
    }
}
</script>
</body>
</html>

您正在获取异常,因为它在加载canvas对象之前尝试设置onmouseover事件。