【问题标题】:Hover last-child but apply style to first-child, nth-child(1), nth-child(2), nth-child(3) [duplicate]悬停最后一个孩子,但将样式应用于第一个孩子,nth-child(1),nth-child(2),nth-child(3)[重复]
【发布时间】:2017-11-28 19:08:45
【问题描述】:

我有 5 个方格。将正方形悬停使其变为绿色。假设我想悬停last-child 并将蓝色应用到first-child, nth-child(1), nth-child(2), nth-child(3) 是否可能不涉及Jquery?

与悬停方块 3 的逻辑相同,然后我希望方块 1+2 变为绿色。

Fiddle

【问题讨论】:

  • 不,这不可能——你需要 JS
  • 您应该标记您的问题 Javascript,而不是 jQuery。如果您将其标记为 jQuery,则意味着您想要一个与 jQuery 相关的答案。
  • Clonkex - 如果它需要 Javascript,我用 Jquery 标记它,因为那时我会寻找 Jquery 答案!
  • Michael Coker > 是的! :) 不知道那个无限符号!它是标准的CSS3 aka。跨浏览器可靠吗?

标签: jquery css sass


【解决方案1】:

如前所述,如果没有 Javascript,这将是不可能的。也许使用 CSS 4?

这是一个使用纯 javascript(没有 jQuery)的快速版本
live demo

// Get all block-items
const items = document.querySelectorAll( '.block-item' );

// Helper function to set active class
const setState = ( index, active ) => {
  if ( index >= 0 && items[ index ] ) {
    // Only add active class when argument active is true
    // Otherwise remove it
    items[ index ].classList.toggle( 'active', active );
  }
}

const onMouseEnter = index => {
  setState( index - 1, true );
  setState( index - 2, true );
};
const onMouseLeave = index => {
  setState( index - 1, false );
  setState( index - 2, false );
};

// Iterate over all items and add event listener
items.forEach( ( item, index ) => {
  item.addEventListener( 'mouseenter', () => onMouseEnter( index ) );
  item.addEventListener( 'mouseleave', () => onMouseLeave( index ) );
} );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 2013-11-28
    • 2021-03-06
    相关资源
    最近更新 更多