【问题标题】:javascript onload not working but onclick is working css draw line [duplicate]javascript onload不工作但onclick工作css画线[重复]
【发布时间】:2012-12-28 07:21:15
【问题描述】:

可能重复:
How to add onload event to a div?

我正在尝试使用 css 和 javascript 画一条线,如下例所示:example。我可以让它与原始内容一起正常工作,但是在尝试修改它然后让它从 html onload 工作 onload 等于它不工作,但它正在处理 onclick 事件。

这是我的 CSS:

.line 
{
    position: absolute;
    height: 0px;
    border-width: 2px 0px 0px 0px;
    border-style: solid;
    border-color: #99aadd;
 }

和javascript:

function createLine2(myline,x1,y1,x2,y2)
{
    if (x2 < x1)
    {
        var temp = x1;
        x1 = x2;
        x2 = temp;
        temp = y1;
        y1 = y2;
        y2 = temp;
    }
    var length = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
    myline.style.width = length+"px";
    var angle = Math.atan((y2-y1)/(x2-x1));
    myline.style.top = y1 + 0.5*length*Math.sin(angle) + "px";
    myline.style.left = x1 - 0.5*length*(1 - Math.cos(angle)) + "px";
    myline.style.MozTransform = myline.style.WebkitTransform = myline.style.OTransform="rotate("+angle+"rad)";
}

最后是不起作用的html:

<div class="line" onload="createLine2(this,100,100,0,0)">test</div><br>

以及有效的 html:

<div class="line" onclick="createLine2(this,100,100,0,0)">test</div><br>

如何让它与 onload 一起工作,我搞砸了什么?

【问题讨论】:

  • DIV 没有加载事件
  • 一个简单的谷歌搜索“div onload”就会给你答案。
  • @musa 那么我怎样才能让它在该 div onload 中创建行
  • 为什么这个标签是 jQuery?

标签: javascript jquery css


【解决方案1】:

在 div 标签上不允许 onload 事件。只允许使用以下标签:

<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

http://www.w3schools.com/jsref/event_onload.asp

【讨论】:

    【解决方案2】:

    如果你使用jquery,我建议使用jquery ready函数。

    .ready( handler ) handler DOM 准备好后执行的函数。

    http://api.jquery.com/ready/

    如果您使用纯 JavaScript,请使用 window.onload

    window.onload = funcRef;

    https://developer.mozilla.org/en-US/docs/DOM/window.onload

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多