I needed this as well, but also wanted a "real" solution. The accepted answer does really not target the question "Detecting click event on padding only" but suggests an intrusive change to the markup.
A "padding click" can be detected simply by retrieving the elements padding settings, computed width and height and compare those values to the mouse click offsets :
function isPaddingClick(element, e) {
var style = window.getComputedStyle(element, null);
var pTop = parseInt( style.getPropertyValue('padding-top') );
var pRight = parseFloat( style.getPropertyValue('padding-right') );
var pLeft = parseFloat( style.getPropertyValue('padding-left') );
var pBottom = parseFloat( style.getPropertyValue('padding-bottom') );
var width = element.offsetWidth;
var height = element.offsetHeight;
var x = parseFloat( e.offsetX );
var y = parseFloat( e.offsetY );
return !(( x > pLeft && x < width - pRight) &&
( y > pTop && y < height - pBottom))
}
demo here -> http://jsfiddle.net/er5w47yf/
jQuery :
$('#element').on('click', function(e) {
if (isPaddingClick(this, e)) {
console.log('click on padding')
} else {
console.log('click on element')
}
})
native :
document.getElementById('element').addEventListener('click', function(e) {
if (isPaddingClick(this, e)) {
console.log('click on padding')
} else {
console.log('click on element')
}
}, false)
For convenience, this can be turned into a jQuery pseudo event handler :
(function($) {
var isPaddingClick = function(element, e) {
var style = window.getComputedStyle(element, null);
var pTop = parseInt( style.getPropertyValue('padding-top') );
var pRight = parseFloat( style.getPropertyValue('padding-right') );
var pLeft = parseFloat( style.getPropertyValue('padding-left') );
var pBottom = parseFloat( style.getPropertyValue('padding-bottom') );
var width = element.offsetWidth;
var height = element.offsetHeight;
var x = parseFloat( e.offsetX );
var y = parseFloat( e.offsetY );
return !(( x > pLeft && x < width - pRight) &&
( y > pTop && y < height - pBottom))
}
$.fn.paddingClick = function(fn) {
this.on('click', function(e) {
if (isPaddingClick(this, e)) {
fn()
}
})
return this
}
}(jQuery));
Now paddingClick
works "natively" :
$('#element').paddingClick(function() {
console.log('padding click')
})
demo -> http://jsfiddle.net/df1ck59r/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…