是否可以在特定的DIV中设置超链接样式?

Is it possible to set hyperlink style within a specific DIV only

本文关键字:设置 超链接 样式 DIV 是否      更新时间:2023-09-26

我正在制作一个纯javascript web应用程序(没有JQuery),在运行时生成所有内容。没有CSS文件需要加载,所有的样式都是由JS生成的。

例如:

function newParagraph(content,x,y,w,h)
{
    var obj = document.createElement("div");
    obj.style.position = "absolute";
    obj.style.left = x + "px";
    obj.style.top = y + "px";
    obj.style.width = w + "px";
    obj.style.height = h + "px";
    obj.style.fontFamily = ..... some web font
    obj.style.fontSize = "20px";
    obj.style.fontWeight = "normal";
    obj.style.fontVariant = "small-caps";
    .... etc ....
    obj.innerHTML = content;
    return obj;
}

上面的函数将创建一个div对象,指定大小和绝对位置,将设置字体样式并将段落内容放在innerHTML中。

此内容可能包含object。

我知道我可以在页面css设置超链接样式。我不想那样。我想只在特定DIV对象的范围内设置超链接样式。所以不同的DIV对象会有不同样式的超链接。

这是可能的吗?如果是,怎么做?

你可以用不同的方式来做,但默认情况下你不应该在内联中做。

一种方法是用JavaScript模拟
<a
  href="/path/file.html"
  onMouseOver="this.style.color='#0F0'"
  onMouseOut="this.style.color='#00F'"
 >YourLink</a>

用Html也可以做到这一点。参见W3.org (http://www.w3.org/TR/2002/WD-css-style-attr-20020515)的例2.3

 <a href="http://www.w3.org/"
      style="{color: #900}
      :link {background: #ff0}
      :visited {background: #fff}
      :hover {outline: thin red solid}
      :active {background: #00f}">...</a>

从这些信息中,你可以用JavaScript设置样式或在你的方法中使用JavaScript设置OnMouse函数。

从脚本中设置href,对于特定的href,可以使用CSS属性选择器,如

a[href^="http://stackoverflow.com"] { 
    color: red; 
    font-family: calibri;
    font-size: 24px;
    text-decoration: none;
}

它确保只有href="http://stackoverflow.com"被样式化。

好的,我找到了解决方案,但如果有人有更好的想法,请张贴答案,我将接受它!

在这里:

function newParagraph(content,x,y,w,h)
{
    var obj = document.createElement("div");
    obj.style.position = "absolute";
    obj.style.left = x + "px";
    obj.style.top = y + "px";
    .... etc ....
    obj.innerHTML = content;
    var childobj = obj.firstChild;
    while(childobj)
    {
        if( childobj.href !== undefined ) // this has hyperlink
            childobj.style.color = ..... hyperlink color ....
        childobj = childobj.nextSibling;
    }
    return obj;
}