简体   繁体   English

使用PHP更改CSS不透明度

[英]Change CSS opacity with PHP

So I have a heart icon that changes when you hover over it. 所以我有一个心脏图标,当您将鼠标悬停在上面时,它会发生变化。 Its fade into a full heart, instead of a stroke. 它淡化了一颗饱满的心,而不是中风。 Now for my project if you already liked the heart it would be solid pink by default. 现在,对于我的项目,如果您已经喜欢心脏,则默认情况下它将为纯粉红色。 So what I planned on doing was check if the user liked it then raise the opacity. 所以我打算做的是检查用户是否喜欢它,然后提高不透明度。 Because the solid icon goes from 0.1 to 1 on hover. 因为实心图标在悬停时从0.1变为1 The issue is I can't figure out how to set the if else statement. 问题是我不知道如何设置if else语句。

<div class="post">
<? if($_SESSION['loggedIn'] == true): ?>
<a href="likes.php?id=<?php echo $post['id'];?>">
<div class="icons">
<i class="fa fa-heart-o"></i>
<i class="fa fa-heart" ></i>
</div>
</a>
<? endif; ?>

That's what I currently have. 那就是我目前所拥有的。 What I'm trying to do is if the user liked it, it would be true. 我想做的是,如果用户喜欢它,那将是正确的。 Then 然后

if(usr_liked == true){
  echo 'opacity: 1';
} 

And that would lie in the style attribute in the heart. 那将在于内心的风格属性。 So how would I do this? 那我该怎么做呢? I can't seem to figure it out with the alternative if else statement to display HTML. 我似乎无法用if语句来显示HTML来弄清楚。

It's not possible to modify DOM styling, such as opacity in your case with PHP alone. 单独使用PHP不可能修改DOM样式,例如您的情况下的不透明性。 You would want to do this with Javascript. 您可能想使用Javascript做到这一点。 One way that I've always done this is by simply calling a piece of Javascript code in a way similar to: 我一直做到这一点的一种方法是,以类似于以下方式简单地调用一段Javascript代码:

<?php if (usr_liked == true) { ?>
    <script>
        document.getElementById("heart").style.opacity = 1.0;' .
    </script>';
<?php } ?>

I hope this helps. 我希望这有帮助。 :) :)

Note: I changed my original post as there was an error I found with it. 注意:由于发现错误,我更改了原始帖子。

You need PHP when loading the page 加载页面时需要PHP

<? if(usr_liked == true){ ?>
    <i class="heart liked"></div>
<? } else { ?>
    <i class="heart not-liked"></div>
<? } ?>

and jQuery to change class if it is clicked 和jQuery更改类(如果单击)

<script>
    $('.heart.not-liked').addClass('liked').removeClass('not-liked');
    $('.heart.liked').addClass('not-liked').removeClass('liked');
</script>

Your css should be 您的CSS应该是

.heart.not-liked {
    color: grey;
}

.heart.liked {
    color: red;
}

The jQuery function could be better. jQuery函数可能会更好。 But it works. 但这有效。 Note: the jQuery function does not do anything with the database. 注意:jQuery函数对数据库不执行任何操作。 You need to write an AJAX post for that. 您需要为此写一个AJAX帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM