【问题标题】:Clicking on an item affecting hover area of other element in ios safari & chrome在ios safari和chrome中单击影响其他元素悬停区域的项目
【发布时间】:2020-07-04 02:38:22
【问题描述】:

关于我的应用的一些背景信息:

我正在使用简单的 create-react-app 样板,并有一个按钮列表,每个按钮都有一个关闭图标和文本。单击关闭图标时,该按钮将从列表中删除。

CSS 效果:我在悬停的按钮上应用了线通效果。


问题:

在 ios safari/chrome 上,如果我删除第一个按钮;悬停效果添加到第二个按钮。这在 Android Chrome 中不会发生。

问题的 GIF:


与问题相关的代码:

组件:

export default function App() {
  const [items, updateItem] = React.useState(["apple", "ball", "cat"]);

  const removeItem = itemToBeRemoved => {
    updateItem(currentItems =>
      currentItems.filter(currentItem => !currentItem.includes(itemToBeRemoved))
    );
  };
  return (
    <div className="filters">
      {items.map(item => (
        <a key={item}>
          <span onClick={() => removeItem(item)}>&#x2715;</span>
          <span>{item}</span>
        </a>
      ))}
    </div>
  );
}

样式:

.filters {
  margin: 0 -3px;
  max-width: 100%;
}

a {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  border-radius: 3px;
  border: 1px solid transparent;
  min-height: 30px;
  word-wrap: break-word;
  padding: 5px 12px;
  line-height: 1.2rem;
  background-color: #eee;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s ease;
  margin: 2px 3px;
  padding: 5px 8px;
  font-size: 0.85rem;
}

a:hover,
a:focus {
  background-color: #ccc;
}

a:focus {
  outline: 0;
  border-color: 1px solid blue;
  box-shadow: 0 0 0 2px #0000ff;
}

a span:first-child {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

a span:last-child {
  display: flex;
  height: 100%;
  top: 0;
  align-items: center;
  border-left: 1px solid gray;
  padding-left: 8px;
  margin-left: 8px;
}

a:hover span:last-child,
a:focus span:last-child {
  text-decoration: line-through;
}

代码沙盒链接:https://codesandbox.io/s/suspicious-swanson-o5jgi


我的理解:

Safari 假设指针停留在同一个位置直到下一次点击(在不同的位置),这就是为什么我们在下一个按钮中看到悬停状态的原因。如果我错了,请告诉我。

【问题讨论】:

  • 嘿,@keikai 我不认为它与key 相关,因为所有的键都是不同且唯一的。
  • 您的理解似乎是正确的。即使使用纯 HTML 按钮(无 React)也会出现此问题。

标签: javascript css reactjs cross-browser


【解决方案1】:

这可能是由于 key 属性而发生的,我认为在您的情况下,键应该是数组上属性的索引,而不是对象本身,试一试:)

【讨论】:

  • 他们key 不是问题所在。这显然是 iOS 的一个众所周知的问题,与 React 无关。此外,键通常应该是唯一的,除非您知道列表将是静态的,否则应避免使用索引作为键,但由于用户可以从任何地方删除项目,因此在此处使用索引会导致问题。 OP 也没有使用对象作为键,而是使用字符串。
猜你喜欢
  • 2012-10-01
  • 2011-05-29
  • 2019-01-27
  • 2022-10-30
相关资源
最近更新 更多