【问题标题】:Search bar which highlights text突出显示文本的搜索栏
【发布时间】:2020-08-02 21:07:07
【问题描述】:

我想要一个搜索栏来搜索值并在我的网页中突出显示该特定值。我制作了一个导航栏,其中有一个 ID 为“btn”的搜索按钮和一个 ID 为“InputVal”的文本框。我希望我的文本框值被搜索并在我的网页(段落)中突出显示。

我的 HTML 代码:

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Search</title>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Dropdown
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="#">Action</a>
                        <a class="dropdown-item" href="#">Another action</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">Something else here</a>
                    </div>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
                </li>
            </ul>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"
                    id="inputVal">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="btn">Search</button>
            </form>
        </div>
    </nav>


    <p style="font-size: 25px;" class="mt-5">
        HMS Royal Oak was one of five British Revenge-class battleships built for the Royal Navy during the First World
        War. Launched on 17 November 1914, the ship first saw combat at the Battle of Jutland. On 14 October 1939, she
        was torpedoed by the German submarine U-47 while anchored at Scapa Flow in Orkney, Scotland; 835 were killed
        that night or died later of their wounds. The loss of the outdated ship—the first of the five Royal Navy
        battleships and battlecruisers sunk in the Second World War—did little to affect the numerical superiority
        enjoyed by the British navy and its allies, but the sinking had a considerable effect on wartime morale. Günther
        Prien, the U-boat commander, became the first German submarine officer to be awarded the Knight's Cross of the
        Iron Cross. Demonstrating that the German navy was capable of bringing the war to British home waters, the raid
        resulted in rapid changes to dockland security and the construction of the Churchill Barriers around Scapa Flow.
    </p>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
    <script src="search.js"></script>


</body>

</html>

Output image of my above code

我的 JS 代码(Jquery):

$(document).ready(function () {
    $('#btn').click( // if someone clicks the button
        function () {
            let bodyTxt = $("p").text() // Takes the paragraph text
            let input = $("#inputVal").val() //Takes the textbox text
            if (bodyTxt.includes(input)) { //checking if my paragraph text includes my search text

                $(bodyTxt).css("background-color", "yellow"); // error in this line. I want to set css properties for my searched text.
            }
            else {
                alert("not found");
            }
        }
    )
});

我的 JavaScipt 代码出现错误。我想为搜索到的文本设置 css 属性(背景颜色:黄色;)。

【问题讨论】:

  • 您正试图通过带有$(bodyTxt) 的内部文本来选择一个html 元素。但您只能按 id 或 class 选择。试试$("p:contains('" + input+ "')").css("background-color", "yellow");

标签: javascript jquery html css


【解决方案1】:

您正试图通过带有$(bodyTxt) 的内部文本来选择一个html 元素。您想找到包含搜索文本的元素

试试

$("p:contains('" + input + "')").css("background-color", "yellow");

而不是

$(bodyTxt).css("background-color", "yellow");

您的整个代码可能如下所示

$(document).ready(function () {
$('#btn').click( // if someone clicks the button
    function () {
        let input = $("#inputVal").val() //Takes the textbox textmy search text

        $("p:contains('" + input + "')").css("background-color", "yellow");

    }
)

请记住,它将Match Case。如果您想找到适合输入的任何内容,无论是小写还是大写,都必须使用toLowerCase

在这里工作jsFiddle

【讨论】:

  • 谢谢,但这会突出显示整个文本,因为我只有一个

    标签

  • 我希望只突出显示我搜索的文本,但它会突出显示整个文本,因为我只有一个

    标签。你能帮我做吗

  • 我不想选择元素。我只想选择搜索到的文本
  • 检查是否对您有帮助:stackoverflow.com/questions/31592132/…
  • 告诉我如何突出显示在我的网页中搜索的特定文本。
【解决方案2】:

我实际上想评论它,但我的观点很少,无论如何我觉得这个不错的JS Fiddle 实际上也可能工作得很好,它包括带有 ID 的 div 或容器。这是显示的JS代码。 Click the link 了解更多详情,如 HTML 等。

function highlightSearch() {
var text = document.getElementById("query").value;
var query = new RegExp("(\\b" + text + "\\b)", "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>$1</span>");
document.getElementById("searchtext").innerHTML = newe;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2017-12-11
    • 2023-04-08
    • 2022-01-16
    • 2013-10-25
    • 2012-06-25
    相关资源
    最近更新 更多