我有侧面标签覆盖。我希望能够单击一个并对其执行某些操作,但我无法让我的事件处理程序注册正确的div。
class MY_Class {
/** @var float Cart grand total. */
public $total;
/**
* Get total.
*
* @return array
*/
public function get_total() {
return $this->total;
}
public function set_total($total) {
$this->total = $total;
}
}
当我单击蓝色或棕色选项卡时,只会调用browntab的事件处理程序。我该如何解决这个问题?
答案 0 :(得分:0)
您的问题是,即使您可以看到两个标签(因为它们的背景部分透明),.brownTab__container
元素与.blueTab__container
重叠,因为它们位于完全相同的位置,因此你总是点击那个。您可以使用开发人员工具的检查器来查看。
您的问题的一个解决方案是实际创建看起来像标签的不同,非重叠元素。可能类似于this或类似this。
另一种解决方案可能是使用单个HTML元素和所有选项卡的单个背景图像,获取所单击像素的颜色并使用它来区分所单击的选项卡。像这样:
const message = document.getElementById('message');
// Get the tabs element:
const tabs = document.getElementById('tabs');
// Get its computed styles:
const style = window.getComputedStyle(tabs);
// Extract the background-image's url:
const backgroundImage = style.getPropertyValue('background-image');
const url = backgroundImage.substring(5, backgroundImage.length - 2);
// Create an image with that url:
const img = document.createElement('IMG');
img.src = url;
// Create a canvas with the original size of the image:
const canvas = document.createElement('CANVAS');
const width = canvas.width = 1;
const height = canvas.height = 123;
// Draw that image on it:
canvas.getContext('2d').drawImage(img, 0, 0, width, height);
// Listen for click events:
document.getElementById('tabs').addEventListener('click', (e) => {
// Get clicked pixel's RGBA value, taking into account the image on the tabs element is
// repeated, while the one on the canvas it's not:
const rgba = canvas.getContext('2d').getImageData(e.offsetX % width, e.offsetY % height, 1, 1).data;
// Set color thresholds for each tab (as in your images the colors are not uniform as
// they are here:
if (rgba[2] > 200) {
message.innerText = 'You clicked the blue tab.';
} else if (rgba[2] < 150 && rgba[1] > 50) {
message.innerText = 'You clicked the brown tab.';
} else if (rgba[1] > 200) {
message.innerText = 'You clicked the gold tab.';
} else if (rgba[1] < 50) {
message.innerText = 'You clicked the purple tab.';
} else {
message.innerText = 'Unknown tab clicked.';
}
});
body {
position: relative;
margin: 0;
height: 800px;
}
#message {
position: fixed;
top: 0;
left: 0;
right: 90px;
padding: 16px;
font-size: 32px;
}
#tabs {
position: absolute;
width: 90px;
height: 100%;
top: 0;
right: 0;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAB7CAYAAAC1rOouAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAAqSURBVChTYzAOPfN/kBJnGtIGK/H+yYbBSpzRBjkSRNzUTkfmDhyR9h8AMPtPIMUTD3YAAAAASUVORK5CYII=);
}
<div id="message"></div>
<div id="tabs"></div>
请注意,使用第一种方法,可以更轻松地添加其他效果和功能,例如悬停/主动/焦点样式,添加/删除标签,移动标签,拖动标签......