HTML DOM Base target 属性

htmlweb developmentfront end technology更新于 2025/9/21 15:08:17

HTML DOM Base target 属性与 HTML <base> 元素关联。它用于设置或返回 <base> 元素的 target 属性值。target 属性用于指定超链接的打开位置。它可以在页面本身或新页面中打开。

属性

以下是目标属性的值 −

属性值描述
_blank在新窗口中打开链接。
_self在点击链接的同一框架中打开链接。这是默认行为。
_parent在父框架集中打开链接。
_top在窗口的整个主体中打开链接。
framename在指定的框架名称中打开链接。

语法

以下是语法 −

返回目标属性 −

baseObject.target

设置目标属性 −

baseObject.target = "_blank|_self|_parent|_top|framename"

示例

让我们看一个 HTML DOM 目标属性的示例 −

<!DOCTYPE html>
<html>
<head>
<base id="Base" target="newframe1" href="https://www.example.com">
</head>
<body>
<p>Click the below button to get the target attribute value</p>
<button onclick="getTarget()">GET TARGET</button>
<p>Click the below button to set the target attribute value</p>
<button onclick="setTarget()">SET TARGET</button>
<p id="Sample"></p>
<script>
   function getTarget() {
      var x = document.getElementById("Base").target;
      document.getElementById("Sample").innerHTML = "Base target for all links is: " + x;
   }
   function setTarget(){
      document.getElementById("Base").target="_blank"
      document.getElementById("Sample").innerHTML="Target has been changed from
      newframe1 to _blank"
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"获取目标" −

点击"设置目标" −

在上面的例子中 −

我们首先创建了两个按钮 GET TARGET 和 SET TARGET,分别用于执行 getTarget() 和 setTarget() 函数 −

<button onclick="getTarget()">GET TARGET</button>
<button onclick="setTarget()">SET TARGET</button>

getTarget() 函数获取 id 为 “Base” 的元素,在本例中即为 <base> 元素。base 元素的 target 属性被赋值给变量 x。然后,target 属性的值显示在 id 为 “Sample” 的段落中。使用 innerHTML() 属性。

function getTarget() {
   var x = document.getElementById("Base").target;
   document.getElementById("Sample").innerHTML = "Base target for all links is: " + x;
}

setTarget() 函数获取 id 为"Base"的元素,在本例中即为 <base> 元素。然后将 <base> 元素的 target 属性设置为 “_blank”,表示它将在新标签页中打开。随后,在与其关联的 id 为 “Sample” 的段落中将显示 “Target 已从 newframe1 更改为 _blank”。


相关文章


有用资源