Изменение цвета SVG при наведении на родительский элемент



У меня есть меню. Каждый пункт меню имеет изображение SVG и текст. SVG встроен с помощью <object>



<ul id="menu-content" class="menu-content collapse out">
<li id="calculator">
<a href="#">
<tr>
<td>
<object type="image/svg+xml" data="assets/calculator.svg">
</object>
</td>
<td class="menu-option">
<span class="menu-option">
Pricing & Services
</span>
</td>
</tr>
</a>
</li>
.....
</ul>


Когда я навожу курсор на пункт меню, Цвет фона этого пункта меняется. Но мне также нужно изменить цвет SVG. На данный момент я знаю, как изменить цвет SVG, когда вы наведете курсор именно на него. Но что делать, когда я навожу курсор на родительский элемент.

1341   4  

4 ответов:

Просто добавьте прослушиватель при наведении на родительский элемент.

var parent = document.querySelector('.parent')
parent.addEventListener('mouseover', function(){
  parent.children[0].style.backgroundColor = 'black';
})
parent.addEventListener('mouseout', function(){
  parent.children[0].style.backgroundColor = 'white';
})
.pretendThisIsTheSVG {\
  background-color: white;
  width:50px;
  height:50px;
  border:1px solid black;
}

.parent {
  width:100px;
  height:100px;
  border:1px solid red;
}
<div class="parent">
  <div class="pretendThisIsTheSVG">
  
  </div>
<div>

Когда вы работаете с svg, Вы можете изменить цвета, используя свойства fill и stroke вместо обычных background-color и color. Например:

li:hover {
  background-color: yellow;
}

li:hover circle {
  fill: violet;
  stroke: blue;
}
<ul id="menu-content" class="menu-content collapse out">
  <li id="calculator">
    <a href="#">
      <tr>
        <td>
          <svg>
            <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
          </svg>
        </td>
        <td class="menu-option">
          <span class="menu-option">
            Pricing & Services
          </span>
        </td>
      </tr>
    </a>
  </li>
 </ul>

Вы не можете сделать это с помощью css, так как правила таблиц стилей не применяются к перекрестным документам. Это можно сделать с помощью javascript, как показано ниже:

var parent = document.querySelector('li')
parent.addEventListener('mouseover', function(event){
  var svg = event.target.querySelector('object').contentDocument;
  var styleElement = svg.createElementNS("http://www.w3.org/2000/svg", "style");
  styleElement.textContent = "svg * { fill: #fff }"; // add whatever you need here
  svg.appendChild(styleElement);
});

Итак, я сделал следующее:: 1) Убедитесь, что приложение выполняется на сервере (я использую http server) 2) в указателе.html я дал идентификатор SVG (id= 'hat') и родительский элемент (id= 'm-i-hat'):

<li id="m-i-hat">
  <a href="#" class="menu-item">
    <object class="menu-icon" id="hat" type="image/svg+xml" data="assets/hat.svg">
    </object>

3) в индексе.js:

$(document).ready(function() {
var hat = document.getElementById("hat");
var parent_hat = document.getElementById("m-i-hat")

// It's important to add an load event listener to the object,
// as it will load the svg doc asynchronously
hat.addEventListener("load",function(){
  // get the inner DOM of image
  var svgDoc = hat.contentDocument;
  // get the inner element by id (in my svg I have a path i need to change with 
  //id='Hat')
  var area = svgDoc.getElementById("Hat");
  // add behaviour
  parent_hat.addEventListener("mouseover",function(){
   area.style.fill = '#fff'
  });
  parent_hat.addEventListener('mouseout', function(){
   area.style.fill = '#50BC99'
  })
});

Comments

    Ничего не найдено.