繁体   English   中英

如何更改div标签的文本

[英]How to change the text of a div tag

我有一个简单的div标签。 您能告诉我如何在onmouseover处理程序中将文本更改为“ mouse in”吗? 并在onmouseout处理程序中“鼠标移出”?

<div id="div1" onmouseover="alert(1);" width="100px" height="200px" border="1">
test
</div>

为什么宽度/高度和边框属性不起作用? 我想将边框设置为1个像素,宽度= 100像素,高度= 200像素。

谢谢。

对于您的CSS,添加以下内容:

/* Using inline-block so we can set w/h while letting elements
   flow around our div */
#div1 { display:inline-block; 
        width:100px; height:200px; 
        border:1px solid #000; }

对于您的Javascript:

/* We start wit a reference to the element via its ID */
var myDiv = document.getElementById("div1");
/* Then we add functions for our events */
myDiv.onmouseover = function() { this.innerHTML = 'mouse over'; }
myDiv.onmouseout  = function() { this.innerHTML = 'mouse out'; }

这给我们留下了非常干净和简约的标记:

<div id="div1">Hover Me!</div>

网上示范

DIV没有width / height / border属性。 您应该改用样式。 甚至最好使用CSS类来设置DIV的样式。

<style type="text/css">
.message {
    width: 100px;
    height: 200px;
    border: solid 1px #000;
}
</style>

<div id="div1" class="message">test</div>

您可能还需要考虑使用jQuery悬停方法,而不是使用mousein / out。 尽管有时将mousein / out更为合适,但我发现通常所需的行为是悬停效果。 使用jQuery之类的JS框架,以浏览器无关的方式进行处理最容易。

 $('#div1').hover( function() {
       $(this).text('mouse in');
   },
   function() {
       $(this).text('mouse out');
   }
 });

试试这个<div style="width:100px;height=200px;border=1px solid black" >your text</div>

使你的CSS工作

只需替换alert(1); 具有Javascript函数。 你可以做

this.innerHTML = 'mouse in'

和类似的onmouseout


至于边界问题,这是因为您必须执行以下操作:

 style="border:1px solid black" 

因为border是CSS元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM