3

Given a div of unknown dimensions how can I draw a solid line from one corner to the diagonally opposite corner without using JavaScript?

I thought the CSS3 calc() function might help me here but it seems you can't pull values from the height and width into another property (e.g. transform or background-image) I was hoping I could do something like:

transform: rotate ( calc(atan(height / width)) rad);

(The calculation is probably wrong but more important is that the syntax is totally invented.)

I am targeting Firefox for this project but would prefer something that will work in any modern browser.

4

3 回答 3

10

您可以使用 SVG:

<svg style='width: 200px; height: 200px;'>
    <line x1="0" y1="200" x2="200" y2="0"
        style="stroke:rgb(255,0,0);stroke-width:2"/>
</svg>

使用百分比坐标,如果需要:

<svg style='width: 100%; height: 100%;'>
    <line x1="0" y1="100%" x2="100%" y2="0"
        style="stroke:rgb(255,0,0);stroke-width:2"/>
</svg>

http://jsfiddle.net/qXKfN/2/

(应该在FF、Chrome、Safari 和 IE >= 9中工作)


在各种浏览器中的各种尺寸下,SVG 可能会被推出其容器。一种解决方案是设置line-height: 0px;. 另一种解决方案,可能是首选解决方案,是position: relative;在容器和position: absolute;SVG 上设置。

http://jsfiddle.net/qXKfN/3/

于 2013-08-08T16:16:25.997 回答
2

或者你可以使用插件: https ://bitbucket.org/stopsopa/jquery.line 我找不到工具来在 div 顶部绘制这样的线条,不会阻止下面的点击,然后创建这个插件的想法是出生。

插件基于 transform-rotate (css3) 和一个 div 元素。

使用:

$.line(0, 0, 500, 1000);

或者

$('selector').line(0, 0, 500, 1000);

您还可以更改线条的颜色或宽度:

$('selector').line(0, 0, 500, 1000, {
   css : {
       borderTop: '5px solid red'
   }
});

你也有回调函数:

$('selector').line(0, 0, 500, 1000, {
   css : {
       borderTop: '5px solid red'
   }
}, function (linediv, opt) {
    linediv.css({
        borderBottom : '1px solid black'
    });
});
于 2014-07-06T23:50:54.497 回答
-1

有时您不想按照建议使用 SVG。这是一个纯 HTML + vanilla JS 代码的示例,用于以任何颜色和宽度从任何X1,Y1到任何绘制一条线。X2,Y2

function drawLine(X1, Y1, X2, Y2, color, width) {
  let x1 = X1, y1 = Y1, x2 = X2, y2 = Y2;
  if (X1 > X2) { x1 = X2; y1 = Y2; x2 = X1; y2 = Y1 }
  const dx = x1 - x2
  const dy = y1 - y2
  const d = Math.sqrt(dx * dx + dy * dy)
  const a = Math.atan(dy / dx)
  
  const element = document.createElement('span')
  element.style = `border-top:solid ${color} ${width}px;position:absolute;top: ${y1}px;left:${x1}px;width:${d}px;height:0;transform:translate(-${d/2}px,0) rotate(${a}rad) translate(${d/2}px,0)`
    document.getElementById('root').appendChild(element)
}

drawLine(10, 10, 100, 200, 'red', 5)
drawLine(15, 150, 300, 30, 'green', 15)
<div id="root" style="position:relative">
</div>

于 2020-11-08T20:37:55.623 回答