如何使按钮转到链接

问题描述 投票:0回答:2

我正在尝试创建一个链接的按钮。所以我有当前的代码:

onEvent("button27", "click", function() {
/* stuff for a link goes here */
});

我该怎么做?我在想类似的东西

setURL("id");

但我不确定。感谢帮助!

javascript
2个回答
0
投票

尝试输入:

<input type=button value="insert button text here" onClick="self.location='Your_URL_here.htm'">

要么:

<button onclick="window.location='http://www.example.com';">Visit Page Now</button>

我认为它应该有效


0
投票

有几种方法可以解决这个问题。

  1. 使用自定义事件处理程序。

<button type="button" id="button27">Go to website</button>

// Create the redirect handler
function handleRedirect(){
    window.location = "your website here";
}

// Make sure the DOM content is loaded
document.addEventListener("DOMContentLoaded", function(event) {
    const btn = document.getElementById("button27");

    // Create a custom event listener
    btn.addEventListener("click", handleRedirect, false);
});

加载页面后,Javascript将在id为button27的按钮上侦听点击事件。然后触发重定向处理程序。

  1. 使用功能。

<button type="button" id="button27" onclick="setURL('your website here');">Go to website</button>

// Create the setURL function
function setURL(url){
    window.location = url;
}

这为您提供了更多控制,因为您可以重复使用多个按钮的功能。虽然当然也可以使用自定义事件处理程序,尽管可能有点棘手。

  1. 将锚链接设置为按钮。

.anchorBtn {
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #33bdef), color-stop(1, #019ad2));
	background:-moz-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:-webkit-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:-o-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:-ms-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:linear-gradient(to bottom, #33bdef 5%, #019ad2 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#33bdef', endColorstr='#019ad2',GradientType=0);
	background-color:#33bdef;
	border:1px solid #057fd0;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	font-family:Arial;
	font-size:15px;
	font-weight:bold;
	padding:6px 24px;
	text-decoration:none;
	text-shadow:0px -1px 0px #5b6178;
}
.anchorBtn:hover {
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #019ad2), color-stop(1, #33bdef));
	background:-moz-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:-webkit-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:-o-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:-ms-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:linear-gradient(to bottom, #019ad2 5%, #33bdef 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#019ad2', endColorstr='#33bdef',GradientType=0);
	background-color:#019ad2;
}
.anchorBtn:active {
	position:relative;
	top:1px;
}
<a href="your website here" class="anchorBtn">Go to website</a>

最后一个解决方案根本不需要Javascript,而且CSS类可以在其他按钮上重复使用。

© www.soinside.com 2019 - 2024. All rights reserved.