1

Всем привет, есть div блок с классом app_account в котором блоки account_item и в них находится svg. Так вот нужно при наведении на блок account_item изменять цвет svg на чёрный, а скорее всего заливку path в нём (может быть ещё circle), а когда убираешь курсор с элемента account_item, то нужно что бы цвет возвращался к предыдущему (ну или заливался белым).

Вот не знаю как это реализовать, на css не смог, на js смог только при наведении изменить цвет и всё. Мне нужно два варианта, как это сделать на javascript и как это сделать на css.

Прошу помочь с этим. Если один элемент, то всё работает (ну там и циклы тогда не нужны будут), если два - работает криво, если три - начинается бесконечный цикл и браузер зависает как только уберёшь курсор с элемента. https://jsfiddle.net/j9uy31xz/

<style>
.app_account{
    background: #212121;
}
.account_item{
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
}
.account_item svg{
    width: 30px;
    height: 30px;
}
.account_item:hover{
    background: white;
    cursor: pointer;
}
</style>
<div class="app_account">
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
</div>
<script type="text/javascript">
    let links = document.getElementsByClassName('account_item');
    for (var i = 0; i < links.length; i++) {
        links[i].addEventListener('mouseenter', function(){
            let link = document.querySelectorAll(':hover')[0];
            let paths = link.getElementsByTagName('path');
            let circles = link.getElementsByTagName('circle');
            for (var i = 0; i < paths.length; i++) {
                path = paths[i];
                circle = circles[i];
                path.style.fill = 'black';
                circle.style.stroke = 'black';
            }
        });
        links[i].addEventListener('mouseleave', function(){
            for (var i = 0; i < links.length; i++) {
                let link = links[i];
                let paths = link.getElementsByTagName('path');
                let circles = link.getElementsByTagName('circle');
                for (var i = 0; i < paths.length; i++) {
                    path = paths[i];
                    circle = circles[i];
                    path.style.fill = 'white';
                    circle.style.stroke = 'white';
                }
            }
        })
    };
</script>

1 ответ 1

2

Да и без JS можно сделать вроде как. Просто добавить в CSS:

.account_item:hover svg{
    filter: invert();
}

Можно на вложенные элементы тоже воздействовать

.account_item:hover svg circle{
    stroke: red;
}

.account_item:hover svg path{
    fill: green;
}

Если очень хочется с JS

 let links = document.querySelectorAll('.account_item');
   
   links.forEach(el => {
        el.addEventListener('mouseenter', function(){
        this.style.background = 'white'
        let path = this.querySelector('svg path') 
        let circle = this.querySelector('svg circle')         
        path.style.fill = 'orange'
        circle.style.stroke = 'red'
      })

        el.addEventListener('mouseleave', function(){
        this.style.background = 'black'
        let path = this.querySelector('svg path') 
        let circle = this.querySelector('svg circle')         
        path.style.fill = 'white'
        circle.style.stroke = 'white'
      })
    })       
    
.app_account{
    background: #212121;
}
.account_item{
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
}
.account_item svg{
    width: 30px;
    height: 30px;
}

.account_item {    
    cursor: pointer;
}
<div class="app_account">
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
</div>

Еще вариант через JS, но уже с добавлением/удалением классов css

 let links = document.querySelectorAll('.account_item');
   
   links.forEach(el => {
        el.addEventListener('mouseenter', function(){
        this.classList.add('active')
      })
        el.addEventListener('mouseleave', function(){
        this.classList.remove('active')
      })
    })       
    
.app_account{
    background: #212121;
}
.account_item{
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
}
.account_item svg{
    width: 30px;
    height: 30px;
}

.account_item {    
    cursor: pointer;
    background: black;
}

.account_item svg path {
  fill: white;
}

.account_item svg circle {    
    stroke: white;
}

.account_item.active {
  background: white;
}


.account_item.active svg path {    
    fill: orange;
}

.account_item.active svg circle {    
    stroke: red;
}
<div class="app_account">
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
    <div class="account_item">
        <svg width="84" height="84" viewBox="0 0 84 84" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="42" cy="42" r="40" stroke-width="4" stroke="white"></circle>
            <path d="M42 72L67.9808 27H16.0192L42 72Z" fill="white"></path>
        </svg>
    </div>
</div>

11
  • Да, помогло. Спасибо. Но вариант с JS тоже пригодился бы, на случай если нужно будет использовать не инверсию а конкретные цвета, например был белый, при наведении стал оранжевый 15 июл 2021 в 8:28
  • всё верно, но это работает только для этого примера. А если вектор будет цветной, инверсия уже не подойдёт. Как изменить на конкретный цвет? + реализация того же на JS было бы очень кстати 15 июл 2021 в 8:38
  • @Иван Креатор fill: orange; вместо filter 15 июл 2021 в 8:39
  • вот именно что fill не работает так как нужно, он распространяется только на задний фон. stroke: orange тоже не очень 15 июл 2021 в 8:40
  • Варьируйте как хотите - .jsfiddle.net/k0Ld9agb 15 июл 2021 в 8:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.