在悬停时更改按钮图像

时间:2018-01-14 05:44:55

标签: html css

我希望有一个包含4个按钮的页面,每个按钮位于页面的四分之一处。按钮应该有一个图像作为背景,当按钮悬停时,此图像应该会改变。这是如何在CSS中完成的?

1 个答案:

答案 0 :(得分:0)

这是一个简单的代码段,可以完成您提出的问题。我使用jQuery的悬停功能来附加事件处理程序来修改图像。

我在容器(主体)上设置0字体大小,填充和边距,并使用50%宽度和50vh(视口高度)来获得4个相等的象限按钮。

$('button').hover(function() {
  $(this).find('img').attr('src', 'http://via.placeholder.com/200x150');
}, function() {
  $(this).find('img').attr('src', 'http://via.placeholder.com/350x150');
});
body {
  font-size: 0;
  margin: 0;
  padding: 0;
}

button {
  box-sizing: border-box;
  width: 50%;
  height: 50vh;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button><img src="http://via.placeholder.com/350x150"></button>
<button><img src="http://via.placeholder.com/350x150"></button>
<button><img src="http://via.placeholder.com/350x150"></button>
<button><img src="http://via.placeholder.com/350x150"></button>