我有一个渲染一系列图像的组件,我有一些用于"悬停蒙版"的CSS,然后覆盖图像,当用户将鼠标悬停在图像上时显示有关该图像的一些信息。
悬停蒙版的尺寸需要与应用首次加载时以及窗口调整大小时的图像尺寸相匹配。
这是基本标记
<div class="call-out-item">
<img src="......">
<div class="hover-mask">Some info about this image</div>
</div>
这是 CSS:
.call-out-item {
position:relative;
display:none;
}
.call-out-item .hover-mask {
position:absolute;
top:0;
left:0;
}
.call-out-item:hover .hover-mask {
opacity: .95;
background: rgba(33,153,232,0.8);
cursor:pointer;
}
这是我的组件代码(不确定 Ember.run.next 的正确用法(!
// other component code here
const {$} = Ember;
init() {
this._super(...arguments);
this.handleResize = function() {
let itemWidth = $(".call-out-item img").width();
let itemHeight = parseInt(itemWidth/1.5);
$(".hover-mask").css({"width":itemWidth,"height":itemHeight});
}.bind(this);
Ember.run.next(this, this.handleResize);
$(window).on('resize', Ember.run.bind(this, this.handleResize));
},
// etc etc
我在 Chrome 和 Firefox 中使用此代码获得了可变结果,所以这里一定做错了什么!
销毁组件时取消绑定事件,否则当用户在其他路由上时,事件将继续触发
initResizeObserver: on("init", function () {
$(window).on('resize', this.handleResize.bind(this));
}),
willDestroyElement () {
this._super(...arguments);
$(window).off("resize");
},
handleResize (e) {
console.log(e)
},
的解决方案。其中一个问题(在 Firefox 中)是上面的代码最初没有计算图像的宽度,所以我现在正在计算父容器的宽度(和高度),并将图像的尺寸设置为 100% 的宽度和高度。
我仍然认为当我调整窗口大小时有一些小故障(有人知道为什么吗?),但我希望这有所帮助!
// component code
import Ember from 'ember';
const {$} = Ember;
export default Ember.Component.extend({
tagName:'div',
classNames:[],
init() {
this._super(...arguments);
this.handleResize = function() {
let itemWidth = parseInt($(".call-out-item").width());
let itemHeight = parseInt(itemWidth/1.5);
$(".hover-mask").css({"width":itemWidth,"height":itemHeight});
};
Ember.run.next(this, this.handleResize);
$(window).on('resize', Ember.run.bind(this, this.handleResize));
},
// rest of code