我目前有一个自定义 DuckDuckGo 搜索栏的代码:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>
当您在框中输入文本并按 Enter 键时,它会自动打开 URL https://duckduckgo.com/?q={{SEARCH}}
。
如果输入了一个域,我怎样才能使这个栏转到一个域?理想情况下,它不会验证域,只是如果它看到模式 xxxx.*
中没有空格的字符串,它就会在新选项卡中打开该页面。
感谢您的帮助!
最佳答案
解决这个问题的一种方法是捕获表单的提交事件,分析输入值,当它是一个域时,用该域打开一个新窗口,并通过返回 false 取消提交。如果不是有效域,则返回 true,让表单照常进行。
您的 HTML:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>
您的 JavaScript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}
关于javascript - 如何使带有 <input> 按钮的搜索栏在输入时打开域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562399/