无法点击 body 背景图片进行重定向

Can not click on body background image for redirect

我的页面内容居中。在 body 上(在这个 div 后面)有一个背景图像,当我点击图像的可见部分时,我必须将用户重定向到其他 link。 问题是 div 超过了 body(应该是这样)。当我单击时,我处于 ​​div 的填充上。我尝试在点击 div 时使用 jquery 进行重定向,但每次点击时都是重定向,我只希望在点击图像背景时使用。

<? php echo '<body style="background-image: url(/tv/banners/main/main_banner_68_1.jpg);" class="tm-isblog" itemscope itemtype="http://schema.org/WebPage" id="background-body"  >';
echo '<div class="tv-content" onclick="showMsg()">';

这是页面内容

<script type="application/javascript">
        function showMsg(item) {
            alert('redirect me now');
    }  </script>

css:

body{margin:0;padding:0 !important;overflow-x:hidden;width:100%;}


.tv-content{margin: auto;width: 100%;border: 0px solid green;padding: 90px 130px;overflow: hidden;}

我相信这就是您要找的东西,我也修复了您在标记中遇到的一些错误。

标记:

<?php 
echo '<body style="background-image: url(/tv/banners/main/main_banner_68_1.jpg);" class="tm-isblog" itemscope itemtype="http://schema.org/WebPage" id="background-body">';
echo '<div class="tv-content" onClick="myFunction()"';
?>

Jquery:

function myFunction() {
// This is your alert message
var r = confirm("Do you really want to leave?");
if (r == true) {
// Where to redirect your users
window.location.href = "anotherwebpage.html";
}
else {
}
document.getElementById("demo").innerHTML = x;
}

当我回答你的问题时,如果用户点击正文,即使点击是在具有 class .tv-content 的容器的 "padding" 内,你想要重定向吗?

您可以通过执行以下操作来实现此目的:

// trigger the click event on body
$('body').on('click', function(e) {
  // get the real click target from the event object
  var elm = $(e.target); 
  // in case this element has no parents with the class, redirect 
  if (!elm.parents().hasClass('tv-content')) {
    console.log('redirect now');
  }
});

我为此做了一个简单的demo

如果我没理解错的话,你想点击正文。那你为什么要使用填充来居中? 内容居中 => body{min-width:100%;最小高度:100vh; 显示:弹性;证明内容:居中;对齐项目:居中;}

如果你想要像填充一样的精确宽度,请使用 'calc' => width: calc(100% - 260px);高度:计算(100% - 180px); 现在你可以点击正文了;您可以使用 jQuery 或仅标记: 在代码片段中

html,body{
  margin:0;
  padding:0 !important;
  overflow-x:hidden;
  width:100%;
  height: 100%;
  
  position:relative;
}

a {
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

div {
  background-color: aqua;
  margin: 90px auto; 
  width: calc(100% - 260px);
  height: 100%;
  
  position: relative;
  z-index: 1;
  
  /*decor*/
  display: flex;
  justify-content: center;
  align-items: center;
}
<body>
  <a href="https://www.google.com"></a>
  <div>
    some text
  </div>
</body>