Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 26.01.2022, 19:20
Интересующийся
Отправить личное сообщение для rita Посмотреть профиль Найти все сообщения от rita
 
Регистрация: 01.06.2020
Сообщений: 22

Стиль для отфильтрованного элемента
ПРИВЕТ!
Кто-нибудь подскажите, как задать стиль для отфильтрованного элемента(filter в скрипте). Через filter.style.color="red" получаю ошибку.
<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<style>
			* {
			box-sizing: border-box;
			}
			body{
			width:1920px;
			height:1024px;
			background-color:#fffdfe;
			font-family: Brandon Grotesque;
			letter-spacing: 0.3px;
			}
			#search_bar {
			height: 40px;
			width: 652px;
			width: 652px;
			border: 1px solid #D6D6D6;
			position: absolute;
			top:48px;
			bottom: 0%;
			margin-left: 349px;
			margin-right: 349px;
			cursor: pointer;
		    font-size: 13px;
			padding-left: 9px;
			}
			#row2 {
			list-style-type: none;
			padding: 0;
			margin: 0;
			display: grid;
			width: 652px;
			}
			#row2 li a {
			border: 1px solid #ddd;
			background-color: #f6f6f6;
			text-decoration: none;
			font-size: 18px;
			color: blue;
			display: inline-block;
			border-right: none;
			border-left: none;
			padding-top: 25px;
			padding-bottom: 25px;
			}
			#row2 li a:hover{
			background-color: #eee;
			color: red;
			}
			#icon1::after {
			content: "\2B07";
			float: right;
			font-size: 23px;
			background-color:aqua;
			display: inline-block;
			}
			#icon1:hover::after {
			content: "\2B06";
			}
			#top2,#top{
			margin-left: 349px;
			margin-right: 349px;
			background: aliceblue;
			width: 652px;
			margin-top: 155px;
			}
			#top2{
			margin-top: 55px;
			}
			#top3{
			align-items: center;
			width: 637px;
			display: inline-block;
			background: #406e97;;
			display: inline-block;
			}
			.column{
			color:background: #323232;
			cursor: pointer;
			display: inline-block;
			padding-right: 12px;
			}
			.column:hover{
			color:#EF5E3A;
			}
			a{text-decoration:none;
			}
			a:hover{
			color:red;
			}
			
			.color{
			color:aqua;
			}		
		</style>

	</head>
	<body>
		
		<input type="text" name="example"  id="search_bar" onkeyup="myFunction()" value="&#128269; Search FAQ" onfocus="value=''">
		<div id="all_top">
			<div id="top"></div>
			<div id="top2"></div>
		</div>
		
		<script>
			var arr2=[
			{name:'HELLO'},
			{name:'GOOD DAY'},
			{name:'MORNING'},
			]
			var text='<ul id="row2">';
			for(var i=0; i<arr2.length; i++){
				text+='<li ><a href="#"><div id="top3">'+arr2[i].name+'</div></a></li>';
			}
			text+='</ul>';
			document.getElementById('top2').innerHTML= text;
			function myFunction() {
				var input, filter, ul, li, a, i, txtValue,b;
				input = document.getElementById("search_bar");
				filter = input.value.toUpperCase();
				//filter.style.color="red";
				console.log(filter+'-it filter');
				ul = document.getElementById("all_top");
				li = ul.getElementsByTagName("li");
				for (i = 0; i < li.length; i++) {
					a = li[i].getElementsByTagName("a")[0];
					txtValue = a.textContent || a.innerText;
					if (txtValue.toUpperCase().indexOf(filter) > -1) {
						li[i].style.display = "";
						} else {
						li[i].style.display = "none";
					}
				}
			}
		</script>
	</body>
</html>

Последний раз редактировалось rita, 26.01.2022 в 20:12.
Ответить с цитированием
  #2 (permalink)  
Старый 26.01.2022, 19:48
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

rita,
сделайте нормальный макет или ждите телепатов.
на всякий случай один id это для одного элемента, если много одинаковых элементов тогда используют class!!!
Ответить с цитированием
  #3 (permalink)  
Старый 26.01.2022, 20:13
Интересующийся
Отправить личное сообщение для rita Посмотреть профиль Найти все сообщения от rita
 
Регистрация: 01.06.2020
Сообщений: 22

Такой подойдет?
Ответить с цитированием
  #4 (permalink)  
Старый 26.01.2022, 21:57
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

rita,
<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    * {
        box-sizing: border-box;
    }
    body {
        width: 1920px;
        height: 1024px;
        background-color: #fffdfe;
        font-family: Brandon Grotesque;
        letter-spacing: .3px;
    }
    #search_bar {
        height: 40px;
        width: 652px;
        width: 652px;
        border: 1px solid #d6d6d6;
        position: absolute;
        top: 48px;
        bottom: 0;
        margin-left: 349px;
        margin-right: 349px;
        cursor: pointer;
        font-size: 13px;
        padding-left: 9px;
    }
    #row2 {
        list-style-type: none;
        padding: 0;
        margin: 0;
        display: grid;
        width: 652px;
    }
    #row2 li a {
        border: 1px solid #ddd;
        background-color: #f6f6f6;
        text-decoration: none;
        font-size: 18px;
        color: blue;
        display: inline-block;
        border-right: none;
        border-left: none;
        padding-top: 25px;
        padding-bottom: 25px;
    }
    #row2 li a:hover {
        background-color: #eee;
        color: red;
    }
    #icon1::after {
        content: '\2B07';
        float: right;
        font-size: 23px;
        background-color: aqua;
        display: inline-block;
    }
    #icon1:hover::after {
        content: '\2B06';
    }
    #top2, #top {
        margin-left: 349px;
        margin-right: 349px;
        background: aliceblue;
        width: 652px;
        margin-top: 155px;
    }
    #top2 {
        margin-top: 55px;
    }
    .top3 {
        align-items: center;
        width: 637px;
        display: inline-block;
        background: #406e97;;
        display: inline-block;
    }
    .column {
        color: background: #323232;
        cursor: pointer;
        display: inline-block;
        padding-right: 12px;
    }
    .column:hover {
        color: #ef5e3a;
    }
    a {
        text-decoration: none;
    }
    a:hover {
        color: red;
    }

    .color {
        color: aqua;
    }
    li.red .top3{
        color: red;
    }
    </style>

</head>

<body>

    <input type="text" name="example" id="search_bar" oninput="myFunction()" value="&#128269; Search FAQ" onfocus="value=''">
    <div id="all_top">
        <div id="top"></div>
        <div id="top2"></div>
    </div>

    <script>
        let arr2 = [{
                name: 'HELLO'
            },
            {
                name: 'GOOD DAY'
            },
            {
                name: 'MORNING'
            },
        ]
        let text = '<ul id="row2">';
        for (let { name } of arr2) {
            text += `<li><a href='#'><div class='top3'>${name}`;
        }

        document.getElementById('top2').innerHTML = text;
        let input = document.getElementById("search_bar"),
            lis = document.querySelectorAll('#row2 > li');

        function myFunction() {
            let txtValue = input.value.trim().toUpperCase();
            lis.forEach(function(li) {
                let textContent = li.textContent;
                let toggle = txtValue && textContent.toUpperCase().indexOf(txtValue) > -1;
                li.classList.toggle('red', toggle)
            })
        }
    </script>
</body>

</html>
Ответить с цитированием
  #5 (permalink)  
Старый 28.01.2022, 15:20
Интересующийся
Отправить личное сообщение для rita Посмотреть профиль Найти все сообщения от rita
 
Регистрация: 01.06.2020
Сообщений: 22

Нужно чтобы цветом выделялись только набранные буквы в инпуте и в массиве ,соответственно, а не все слово.

Последний раз редактировалось rita, 28.01.2022 в 15:38.
Ответить с цитированием
  #6 (permalink)  
Старый 28.01.2022, 15:47
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

Сообщение от rita
Нужно чтобы цветом выделялись только набранные буквы в инпуте и в массиве ,соответственно, а не все слово.
https://javascript.ru/forum/events/7...odstrok-4.html
Ответить с цитированием
  #7 (permalink)  
Старый 28.01.2022, 15:50
Интересующийся
Отправить личное сообщение для rita Посмотреть профиль Найти все сообщения от rita
 
Регистрация: 01.06.2020
Сообщений: 22

Спасибо, но я думаю и так подойдет.
Ответить с цитированием
  #8 (permalink)  
Старый 28.01.2022, 16:19
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

поиск и подсветка совпадений
Сообщение от rita
и так подойдет.
можно, через пробел, несколько образцов для совпадений, регистр не важен.


<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            width: 1920px;
            height: 1024px;
            background-color: #fffdfe;
            font-family: Brandon Grotesque;
            letter-spacing: .3px;
        }
        #search_bar {
            height: 40px;
            width: 652px;
            width: 652px;
            border: 1px solid #d6d6d6;
            position: absolute;
            top: 48px;
            bottom: 0;
            margin-left: 349px;
            margin-right: 349px;
            cursor: pointer;
            font-size: 13px;
            padding-left: 9px;
        }
        #row2 {
            list-style-type: none;
            padding: 0;
            margin: 0;
            display: grid;
            width: 652px;
        }
        #row2 li a {
            border: 1px solid #ddd;
            background-color: #f6f6f6;
            text-decoration: none;
            font-size: 18px;
            color: blue;
            display: inline-block;
            border-right: none;
            border-left: none;
            padding-top: 25px;
            padding-bottom: 25px;
        }
        #row2 li a:hover {
            background-color: #eee;
            color: red;
        }
        #icon1::after {
            content: '\2B07';
            float: right;
            font-size: 23px;
            background-color: aqua;
            display: inline-block;
        }
        #icon1:hover::after {
            content: '\2B06';
        }
        #top2,
        #top {
            margin-left: 349px;
            margin-right: 349px;
            background: aliceblue;
            width: 652px;
            margin-top: 155px;
        }
        #top2 {
            margin-top: 55px;
        }
        .top3 {
            align-items: center;
            width: 637px;
            display: inline-block;
            background: #406e97;
            ;
            display: inline-block;
        }
        .column {
            color: background: #323232;
            cursor: pointer;
            display: inline-block;
            padding-right: 12px;
        }
        .column:hover {
            color: #ef5e3a;
        }
        a {
            text-decoration: none;
        }
        a:hover,
        a:hover mark {
            color: red;
        }
        .color {
            color: aqua;
        }
        mark {
            color: #000000;
        }
    </style>
</head>
<body>
    <input type="text" name="example" id="search_bar" value="???? Search FAQ" onfocus="value=''">
    <div id="all_top">
        <div id="top"></div>
        <div id="top2"></div>
    </div>
    <script>
        let arr2 = [{
                name: 'HELLO'
            },
            {
                name: 'GOOD DAY'
            },
            {
                name: 'MORNING'
            },
        ]
        let text = '<ul id="row2">';
        for (let {
                name
            } of arr2) {
            text += `<li><a href='#'><div class='top3' data-name='${name}'>${name}`;
        }
        document.getElementById('top2').innerHTML = text;
        let search = document.getElementById("search_bar"),
            divs = document.querySelectorAll('#row2 .top3');
        RegExp.escape = s => s.replace(/[[\\^$.|?*+()]/gim, "\\$&");
        function mark(string) {
            const node = document.createElement("mark");
            node.textContent = string;
            return node;
        }
        search.addEventListener('input', function() {
            const parts = search.value.trim().split(/\s+/);
            const pattern = new RegExp(parts.map(RegExp.escape).join("|"), "gi");
            divs.forEach(function(div) {
                let match, index = 0,
                    value = div.dataset.name;
                pattern.lastIndex = 0;
                div.textContent = "";
                if (parts[0].length > 0)
                    while (match = pattern.exec(value))
                        div.append(
                            value.slice(index, index = match.index),
                            mark(value.slice(index, index = pattern.lastIndex))
                        );
                div.append(value.slice(index));
            })
        })
    </script>
</body>
</html>
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
как отследить данные, из поля ввода Блондинка Общие вопросы Javascript 41 30.04.2021 16:55
Другой стиль для мобильной версии win32s (X)HTML/CSS 1 06.11.2019 07:42
Проблема с выборкой нужного элемента для исполнения frolvict jQuery 3 04.08.2011 00:14
onClick эвент для всего документа, кроме отдельно взятого элемента DOM el_erizo Events/DOM/Window 5 19.03.2010 15:09
Применение функции для каждого элемента sergeygerasimov jQuery 2 26.11.2008 11:15