简体   繁体   中英

Is using the HTML style tag bad practice? How else can I accomplish this?

Currently I'm doing something like this:

<?php
if ($x == 0)
  $image = 'background-position: 0px -7px';
else
  $image = 'background-position: 0px -14px';
?>
<a class="asdf" style="<?php echo $image; ?>"></a>

Is this the recommended way to change an image based on a variable in HTML/PHP? Is there any way to refactor this?

Try something like this:

<?php
    $positionClass = ($x == 0) ? 'position1' : 'position2';
?>
<style type="text/css">
    .position1 { background-position: 0px -7px; }
    .position2 { background-position: 0px -14px; }
</style>
<a class="asdf <?php echo $positionClass;?>"></a>

PHP will set which class should be used, and then echo the corresponding class in your HTML. The CSS will be applied with the desired positioning attributes.

If it's part of the style, use css and classes. If it's part of the content, you should be using an img element.

You're code is weird? At the end of the if-statement the position would end up begin -7 or -14px... the first is just nonsense...

thus this code might be 'neat'-er but thats just personal:

<a class="asdf" style="background-position: 0px -<?php echo (($x==0)?'7':'14') ?>px;"></a>

Again, some might argue that this inline tenerary operator might be unreadable, but it does the same thing...

I would probably set a class instead, and change the class via PHP. This way, you are still maintaining style in your CSS, but can choose it with PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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